From b814a39240c0875dd9ca1bdf714559cc31d976a6 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Wed, 16 Aug 2017 13:34:36 -0700 Subject: [PATCH 01/17] Initial checkin. --- apps/fabric-website/package.json | 4 +- common/config/rush/npm-shrinkwrap.json | 747 ++++++- packages/example-app-base/package.json | 4 +- packages/experiments/package.json | 4 +- packages/merge-styles/.npmignore | 22 + packages/merge-styles/.npmrc | 2 + packages/merge-styles/LICENSE | 15 + packages/merge-styles/README.md | 225 ++ packages/merge-styles/api/merge-styles.api.ts | 366 ++++ .../merge-styles/config/api-extractor.json | 6 + packages/merge-styles/gulpfile.js | 45 + packages/merge-styles/karma.config.js | 111 + packages/merge-styles/package.json | 54 + packages/merge-styles/src/IRawStyle.ts | 1916 +++++++++++++++++ packages/merge-styles/src/IStyle.ts | 22 + packages/merge-styles/src/IStyleSet.ts | 5 + packages/merge-styles/src/Stylesheet.ts | 161 ++ packages/merge-styles/src/common/tests.js | 22 + .../merge-styles/src/concatStyleSets.test.ts | 43 + packages/merge-styles/src/concatStyleSets.ts | 33 + packages/merge-styles/src/fontFace.test.ts | 20 + packages/merge-styles/src/fontFace.ts | 11 + .../merge-styles/src/getVendorSettings.ts | 41 + packages/merge-styles/src/index.ts | 34 + packages/merge-styles/src/keyframes.ts | 41 + packages/merge-styles/src/mergeStyleSets.ts | 27 + packages/merge-styles/src/mergeStyles.test.ts | 29 + packages/merge-styles/src/mergeStyles.ts | 36 + packages/merge-styles/src/server.ts | 17 + .../merge-styles/src/styleToClassName.test.ts | 114 + packages/merge-styles/src/styleToClassName.ts | 179 ++ .../src/transforms/expandQuads.test.ts | 37 + .../src/transforms/expandQuads.ts | 31 + .../src/transforms/prefixRules.test.ts | 67 + .../src/transforms/prefixRules.ts | 31 + .../src/transforms/provideUnits.test.ts | 48 + .../src/transforms/provideUnits.ts | 31 + .../src/transforms/rtlifyRules.test.ts | 50 + .../src/transforms/rtlifyRules.ts | 72 + packages/merge-styles/tsconfig.json | 31 + packages/merge-styles/tslint.json | 6 + packages/office-ui-fabric-react/package.json | 4 +- packages/utilities/api/utilities.api.ts | 2 +- packages/utilities/package.json | 2 +- packages/utilities/src/GlobalSettings.ts | 6 +- rush.json | 5 + 46 files changed, 4731 insertions(+), 48 deletions(-) create mode 100644 packages/merge-styles/.npmignore create mode 100644 packages/merge-styles/.npmrc create mode 100644 packages/merge-styles/LICENSE create mode 100644 packages/merge-styles/README.md create mode 100644 packages/merge-styles/api/merge-styles.api.ts create mode 100644 packages/merge-styles/config/api-extractor.json create mode 100644 packages/merge-styles/gulpfile.js create mode 100644 packages/merge-styles/karma.config.js create mode 100644 packages/merge-styles/package.json create mode 100644 packages/merge-styles/src/IRawStyle.ts create mode 100644 packages/merge-styles/src/IStyle.ts create mode 100644 packages/merge-styles/src/IStyleSet.ts create mode 100644 packages/merge-styles/src/Stylesheet.ts create mode 100644 packages/merge-styles/src/common/tests.js create mode 100644 packages/merge-styles/src/concatStyleSets.test.ts create mode 100644 packages/merge-styles/src/concatStyleSets.ts create mode 100644 packages/merge-styles/src/fontFace.test.ts create mode 100644 packages/merge-styles/src/fontFace.ts create mode 100644 packages/merge-styles/src/getVendorSettings.ts create mode 100644 packages/merge-styles/src/index.ts create mode 100644 packages/merge-styles/src/keyframes.ts create mode 100644 packages/merge-styles/src/mergeStyleSets.ts create mode 100644 packages/merge-styles/src/mergeStyles.test.ts create mode 100644 packages/merge-styles/src/mergeStyles.ts create mode 100644 packages/merge-styles/src/server.ts create mode 100644 packages/merge-styles/src/styleToClassName.test.ts create mode 100644 packages/merge-styles/src/styleToClassName.ts create mode 100644 packages/merge-styles/src/transforms/expandQuads.test.ts create mode 100644 packages/merge-styles/src/transforms/expandQuads.ts create mode 100644 packages/merge-styles/src/transforms/prefixRules.test.ts create mode 100644 packages/merge-styles/src/transforms/prefixRules.ts create mode 100644 packages/merge-styles/src/transforms/provideUnits.test.ts create mode 100644 packages/merge-styles/src/transforms/provideUnits.ts create mode 100644 packages/merge-styles/src/transforms/rtlifyRules.test.ts create mode 100644 packages/merge-styles/src/transforms/rtlifyRules.ts create mode 100644 packages/merge-styles/tsconfig.json create mode 100644 packages/merge-styles/tslint.json diff --git a/apps/fabric-website/package.json b/apps/fabric-website/package.json index 36d1129ed4e36e..b4d9adc512357d 100644 --- a/apps/fabric-website/package.json +++ b/apps/fabric-website/package.json @@ -43,7 +43,7 @@ "gutil": "1.6.4", "highlight.js": "^9.6.0", "load-themed-styles-loader": "^0.0.3", - "mocha": "^3.2.0", + "mocha": "^3.3.0", "mocha-loader": "^1.1.1", "node-sass": "^4.5.0", "office-ui-fabric-core": ">=7.1.2 <8.0.0", @@ -57,7 +57,7 @@ "resemblejs": "~2.2.3", "sass-loader": "^6.0.3", "sinon": "^2.3.2", - "source-map-loader": "0.2.1", + "source-map-loader": "^0.2.1", "ts-loader": "^2.0.1", "typescript": "2.4.2", "webpack": "^3.5.1", diff --git a/common/config/rush/npm-shrinkwrap.json b/common/config/rush/npm-shrinkwrap.json index 7c74f3e98b4028..43d2823987586e 100644 --- a/common/config/rush/npm-shrinkwrap.json +++ b/common/config/rush/npm-shrinkwrap.json @@ -9,9 +9,9 @@ "integrity": "sha1-pVZ78Y5vGuhNhjE5j0kzlMJeIdM=" }, "@microsoft/gulp-core-build": { - "version": "2.9.2", - "resolved": "https://registry.npmjs.org/@microsoft/gulp-core-build/-/gulp-core-build-2.9.2.tgz", - "integrity": "sha1-mx/9pcjNJMZZv0AWUWUUQUztB7s=", + "version": "2.9.3", + "resolved": "https://registry.npmjs.org/@microsoft/gulp-core-build/-/gulp-core-build-2.9.3.tgz", + "integrity": "sha1-HJbOC5DAUmm9jMurTY5VskofCVg=", "dependencies": { "@types/chai": { "version": "3.4.34", @@ -156,9 +156,9 @@ "integrity": "sha1-k9LYWMLwL+3wxZSKal4KQ8XjqCU=" }, "@microsoft/gulp-core-build-typescript": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/@microsoft/gulp-core-build-typescript/-/gulp-core-build-typescript-3.3.2.tgz", - "integrity": "sha1-EH8TFHtgW28sUP6rYZTPp9+po4s=" + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@microsoft/gulp-core-build-typescript/-/gulp-core-build-typescript-3.4.0.tgz", + "integrity": "sha1-Fy1A/zaq1nAcju1SmSKbjx0QOQw=" }, "@microsoft/gulp-core-build-webpack": { "version": "1.1.6", @@ -867,11 +867,6 @@ "resolved": "https://registry.npmjs.org/@microsoft/web-library-build/-/web-library-build-3.2.8.tgz", "integrity": "sha1-Nu04s3YW+V7dAVh3WT+eiyJ5PYQ=", "dependencies": { - "@microsoft/gulp-core-build": { - "version": "2.9.3", - "resolved": "https://registry.npmjs.org/@microsoft/gulp-core-build/-/gulp-core-build-2.9.3.tgz", - "integrity": "sha1-HJbOC5DAUmm9jMurTY5VskofCVg=" - }, "@microsoft/gulp-core-build-karma": { "version": "2.3.8", "resolved": "https://registry.npmjs.org/@microsoft/gulp-core-build-karma/-/gulp-core-build-karma-2.3.8.tgz", @@ -886,6 +881,26 @@ "version": "2.9.2", "resolved": "https://registry.npmjs.org/@microsoft/gulp-core-build/-/gulp-core-build-2.9.2.tgz", "integrity": "sha1-mx/9pcjNJMZZv0AWUWUUQUztB7s=" + }, + "camelcase": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", + "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=" + }, + "cliui": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", + "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=" + }, + "window-size": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.2.0.tgz", + "integrity": "sha1-tDFbtCFKPXBY6+7okuE/ok2YsHU=" + }, + "yargs": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-4.6.0.tgz", + "integrity": "sha1-y0BQwBWb+2u2ScD0r1UFJqhGGdw=" } } }, @@ -898,6 +913,58 @@ "version": "2.9.2", "resolved": "https://registry.npmjs.org/@microsoft/gulp-core-build/-/gulp-core-build-2.9.2.tgz", "integrity": "sha1-mx/9pcjNJMZZv0AWUWUUQUztB7s=" + }, + "camelcase": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", + "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=" + }, + "cliui": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", + "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=" + }, + "window-size": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.2.0.tgz", + "integrity": "sha1-tDFbtCFKPXBY6+7okuE/ok2YsHU=" + }, + "yargs": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-4.6.0.tgz", + "integrity": "sha1-y0BQwBWb+2u2ScD0r1UFJqhGGdw=" + } + } + }, + "@microsoft/gulp-core-build-typescript": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/@microsoft/gulp-core-build-typescript/-/gulp-core-build-typescript-3.3.2.tgz", + "integrity": "sha1-EH8TFHtgW28sUP6rYZTPp9+po4s=", + "dependencies": { + "@microsoft/gulp-core-build": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/@microsoft/gulp-core-build/-/gulp-core-build-2.9.2.tgz", + "integrity": "sha1-mx/9pcjNJMZZv0AWUWUUQUztB7s=" + }, + "camelcase": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", + "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=" + }, + "cliui": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", + "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=" + }, + "window-size": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.2.0.tgz", + "integrity": "sha1-tDFbtCFKPXBY6+7okuE/ok2YsHU=" + }, + "yargs": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-4.6.0.tgz", + "integrity": "sha1-y0BQwBWb+2u2ScD0r1UFJqhGGdw=" } } }, @@ -910,6 +977,26 @@ "version": "2.9.2", "resolved": "https://registry.npmjs.org/@microsoft/gulp-core-build/-/gulp-core-build-2.9.2.tgz", "integrity": "sha1-mx/9pcjNJMZZv0AWUWUUQUztB7s=" + }, + "camelcase": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", + "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=" + }, + "cliui": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", + "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=" + }, + "window-size": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.2.0.tgz", + "integrity": "sha1-tDFbtCFKPXBY6+7okuE/ok2YsHU=" + }, + "yargs": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-4.6.0.tgz", + "integrity": "sha1-y0BQwBWb+2u2ScD0r1UFJqhGGdw=" } } }, @@ -953,6 +1040,11 @@ "resolved": "https://registry.npmjs.org/diff/-/diff-3.2.0.tgz", "integrity": "sha1-yc45Okt8vQsFinJck98pkCeGj/k=" }, + "glob": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.1.tgz", + "integrity": "sha1-gFIR3wT6rxxjo2ADBs31reULLsg=" + }, "interpret": { "version": "0.6.6", "resolved": "https://registry.npmjs.org/interpret/-/interpret-0.6.6.tgz", @@ -983,14 +1075,7 @@ "mocha": { "version": "3.4.2", "resolved": "https://registry.npmjs.org/mocha/-/mocha-3.4.2.tgz", - "integrity": "sha1-0O9NMyEm2/GNDWQMmzgt1IvpdZQ=", - "dependencies": { - "glob": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.1.tgz", - "integrity": "sha1-gFIR3wT6rxxjo2ADBs31reULLsg=" - } - } + "integrity": "sha1-0O9NMyEm2/GNDWQMmzgt1IvpdZQ=" }, "ms": { "version": "0.7.2", @@ -1043,11 +1128,6 @@ "version": "0.2.10", "resolved": "https://registry.npmjs.org/async/-/async-0.2.10.tgz", "integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E=" - }, - "yargs": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz", - "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=" } } }, @@ -1065,6 +1145,11 @@ "version": "0.0.2", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz", "integrity": "sha1-t5Zpu0LstAn4PVg8rVLKF+qhZD8=" + }, + "yargs": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz", + "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=" } } }, @@ -1795,6 +1880,51 @@ } } }, + "@rush-temp/merge-styles": { + "version": "file:projects/merge-styles", + "dependencies": { + "async": { + "version": "0.9.2", + "bundled": true + }, + "commander": { + "version": "2.9.0", + "bundled": true + }, + "debug": { + "version": "2.6.0", + "bundled": true + }, + "diff": { + "version": "3.2.0", + "bundled": true + }, + "glob": { + "version": "7.1.1", + "bundled": true + }, + "mocha": { + "version": "3.3.0", + "bundled": true + }, + "ms": { + "version": "0.7.2", + "bundled": true + }, + "source-map": { + "version": "0.1.43", + "bundled": true + }, + "source-map-loader": { + "version": "0.2.1", + "bundled": true + }, + "supports-color": { + "version": "3.1.2", + "bundled": true + } + } + }, "@rush-temp/office-ui-fabric-react": { "version": "file:projects/office-ui-fabric-react", "dependencies": { @@ -3472,9 +3602,9 @@ } }, "babel-code-frame": { - "version": "6.22.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.22.0.tgz", - "integrity": "sha1-AnYgvuVnqIwyVhV05/0IAdMxGOQ=" + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=" }, "backo2": { "version": "1.0.2", @@ -4575,9 +4705,9 @@ "integrity": "sha1-s55/HabrCnW6nBcySzR1PEfgZU0=" }, "dns-packet": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-1.2.1.tgz", - "integrity": "sha512-eisukPHpsFmhEIDnm2mECIiT0huapmdkC0AH1Lvt613Kz2v1kwolrkecvguFazrqnpxvgYdtcMFTsmQzAeRXZQ==" + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-1.2.2.tgz", + "integrity": "sha512-kN+DjfGF7dJGUL7nWRktL9Z18t1rWP3aQlyZdY8XlpvU3Nc6GeFTQApftcjtWKxAZfiggZSGrCEoszNgvnpwDg==" }, "dns-txt": { "version": "2.0.2", @@ -5347,6 +5477,549 @@ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, + "fsevents": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.1.2.tgz", + "integrity": "sha512-Sn44E5wQW4bTHXvQmvSHwqbuiXtduD6Rrjm2ZtUEGbyrig+nUH3t/QD4M4/ZXViY556TBpRgZkHLDx3JxPwxiw==", + "optional": true, + "dependencies": { + "abbrev": { + "version": "1.1.0", + "bundled": true, + "optional": true + }, + "ajv": { + "version": "4.11.8", + "bundled": true, + "optional": true + }, + "ansi-regex": { + "version": "2.1.1", + "bundled": true + }, + "aproba": { + "version": "1.1.1", + "bundled": true, + "optional": true + }, + "are-we-there-yet": { + "version": "1.1.4", + "bundled": true, + "optional": true + }, + "asn1": { + "version": "0.2.3", + "bundled": true, + "optional": true + }, + "assert-plus": { + "version": "0.2.0", + "bundled": true, + "optional": true + }, + "asynckit": { + "version": "0.4.0", + "bundled": true, + "optional": true + }, + "aws-sign2": { + "version": "0.6.0", + "bundled": true, + "optional": true + }, + "aws4": { + "version": "1.6.0", + "bundled": true, + "optional": true + }, + "balanced-match": { + "version": "0.4.2", + "bundled": true + }, + "bcrypt-pbkdf": { + "version": "1.0.1", + "bundled": true, + "optional": true + }, + "block-stream": { + "version": "0.0.9", + "bundled": true + }, + "boom": { + "version": "2.10.1", + "bundled": true + }, + "brace-expansion": { + "version": "1.1.7", + "bundled": true + }, + "buffer-shims": { + "version": "1.0.0", + "bundled": true + }, + "caseless": { + "version": "0.12.0", + "bundled": true, + "optional": true + }, + "co": { + "version": "4.6.0", + "bundled": true, + "optional": true + }, + "code-point-at": { + "version": "1.1.0", + "bundled": true + }, + "combined-stream": { + "version": "1.0.5", + "bundled": true + }, + "concat-map": { + "version": "0.0.1", + "bundled": true + }, + "console-control-strings": { + "version": "1.1.0", + "bundled": true + }, + "core-util-is": { + "version": "1.0.2", + "bundled": true + }, + "cryptiles": { + "version": "2.0.5", + "bundled": true, + "optional": true + }, + "dashdash": { + "version": "1.14.1", + "bundled": true, + "optional": true, + "dependencies": { + "assert-plus": { + "version": "1.0.0", + "bundled": true, + "optional": true + } + } + }, + "debug": { + "version": "2.6.8", + "bundled": true, + "optional": true + }, + "deep-extend": { + "version": "0.4.2", + "bundled": true, + "optional": true + }, + "delayed-stream": { + "version": "1.0.0", + "bundled": true + }, + "delegates": { + "version": "1.0.0", + "bundled": true, + "optional": true + }, + "ecc-jsbn": { + "version": "0.1.1", + "bundled": true, + "optional": true + }, + "extend": { + "version": "3.0.1", + "bundled": true, + "optional": true + }, + "extsprintf": { + "version": "1.0.2", + "bundled": true + }, + "forever-agent": { + "version": "0.6.1", + "bundled": true, + "optional": true + }, + "form-data": { + "version": "2.1.4", + "bundled": true, + "optional": true + }, + "fs.realpath": { + "version": "1.0.0", + "bundled": true + }, + "fstream": { + "version": "1.0.11", + "bundled": true + }, + "fstream-ignore": { + "version": "1.0.5", + "bundled": true, + "optional": true + }, + "gauge": { + "version": "2.7.4", + "bundled": true, + "optional": true + }, + "getpass": { + "version": "0.1.7", + "bundled": true, + "optional": true, + "dependencies": { + "assert-plus": { + "version": "1.0.0", + "bundled": true, + "optional": true + } + } + }, + "glob": { + "version": "7.1.2", + "bundled": true + }, + "graceful-fs": { + "version": "4.1.11", + "bundled": true + }, + "har-schema": { + "version": "1.0.5", + "bundled": true, + "optional": true + }, + "har-validator": { + "version": "4.2.1", + "bundled": true, + "optional": true + }, + "has-unicode": { + "version": "2.0.1", + "bundled": true, + "optional": true + }, + "hawk": { + "version": "3.1.3", + "bundled": true, + "optional": true + }, + "hoek": { + "version": "2.16.3", + "bundled": true + }, + "http-signature": { + "version": "1.1.1", + "bundled": true, + "optional": true + }, + "inflight": { + "version": "1.0.6", + "bundled": true + }, + "inherits": { + "version": "2.0.3", + "bundled": true + }, + "ini": { + "version": "1.3.4", + "bundled": true, + "optional": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true + }, + "is-typedarray": { + "version": "1.0.0", + "bundled": true, + "optional": true + }, + "isarray": { + "version": "1.0.0", + "bundled": true + }, + "isstream": { + "version": "0.1.2", + "bundled": true, + "optional": true + }, + "jodid25519": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "jsbn": { + "version": "0.1.1", + "bundled": true, + "optional": true + }, + "json-schema": { + "version": "0.2.3", + "bundled": true, + "optional": true + }, + "json-stable-stringify": { + "version": "1.0.1", + "bundled": true, + "optional": true + }, + "json-stringify-safe": { + "version": "5.0.1", + "bundled": true, + "optional": true + }, + "jsonify": { + "version": "0.0.0", + "bundled": true, + "optional": true + }, + "jsprim": { + "version": "1.4.0", + "bundled": true, + "optional": true, + "dependencies": { + "assert-plus": { + "version": "1.0.0", + "bundled": true, + "optional": true + } + } + }, + "mime-db": { + "version": "1.27.0", + "bundled": true + }, + "mime-types": { + "version": "2.1.15", + "bundled": true + }, + "minimatch": { + "version": "3.0.4", + "bundled": true + }, + "minimist": { + "version": "0.0.8", + "bundled": true + }, + "mkdirp": { + "version": "0.5.1", + "bundled": true + }, + "ms": { + "version": "2.0.0", + "bundled": true, + "optional": true + }, + "node-pre-gyp": { + "version": "0.6.36", + "bundled": true, + "optional": true + }, + "nopt": { + "version": "4.0.1", + "bundled": true, + "optional": true + }, + "npmlog": { + "version": "4.1.0", + "bundled": true, + "optional": true + }, + "number-is-nan": { + "version": "1.0.1", + "bundled": true + }, + "oauth-sign": { + "version": "0.8.2", + "bundled": true, + "optional": true + }, + "object-assign": { + "version": "4.1.1", + "bundled": true, + "optional": true + }, + "once": { + "version": "1.4.0", + "bundled": true + }, + "os-homedir": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "os-tmpdir": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "osenv": { + "version": "0.1.4", + "bundled": true, + "optional": true + }, + "path-is-absolute": { + "version": "1.0.1", + "bundled": true + }, + "performance-now": { + "version": "0.2.0", + "bundled": true, + "optional": true + }, + "process-nextick-args": { + "version": "1.0.7", + "bundled": true + }, + "punycode": { + "version": "1.4.1", + "bundled": true, + "optional": true + }, + "qs": { + "version": "6.4.0", + "bundled": true, + "optional": true + }, + "rc": { + "version": "1.2.1", + "bundled": true, + "optional": true, + "dependencies": { + "minimist": { + "version": "1.2.0", + "bundled": true, + "optional": true + } + } + }, + "readable-stream": { + "version": "2.2.9", + "bundled": true + }, + "request": { + "version": "2.81.0", + "bundled": true, + "optional": true + }, + "rimraf": { + "version": "2.6.1", + "bundled": true + }, + "safe-buffer": { + "version": "5.0.1", + "bundled": true + }, + "semver": { + "version": "5.3.0", + "bundled": true, + "optional": true + }, + "set-blocking": { + "version": "2.0.0", + "bundled": true, + "optional": true + }, + "signal-exit": { + "version": "3.0.2", + "bundled": true, + "optional": true + }, + "sntp": { + "version": "1.0.9", + "bundled": true, + "optional": true + }, + "sshpk": { + "version": "1.13.0", + "bundled": true, + "optional": true, + "dependencies": { + "assert-plus": { + "version": "1.0.0", + "bundled": true, + "optional": true + } + } + }, + "string_decoder": { + "version": "1.0.1", + "bundled": true + }, + "string-width": { + "version": "1.0.2", + "bundled": true + }, + "stringstream": { + "version": "0.0.5", + "bundled": true, + "optional": true + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true + }, + "strip-json-comments": { + "version": "2.0.1", + "bundled": true, + "optional": true + }, + "tar": { + "version": "2.2.1", + "bundled": true + }, + "tar-pack": { + "version": "3.4.0", + "bundled": true, + "optional": true + }, + "tough-cookie": { + "version": "2.3.2", + "bundled": true, + "optional": true + }, + "tunnel-agent": { + "version": "0.6.0", + "bundled": true, + "optional": true + }, + "tweetnacl": { + "version": "0.14.5", + "bundled": true, + "optional": true + }, + "uid-number": { + "version": "0.0.6", + "bundled": true, + "optional": true + }, + "util-deprecate": { + "version": "1.0.2", + "bundled": true + }, + "uuid": { + "version": "3.0.1", + "bundled": true, + "optional": true + }, + "verror": { + "version": "1.3.6", + "bundled": true, + "optional": true + }, + "wide-align": { + "version": "1.1.2", + "bundled": true, + "optional": true + }, + "wrappy": { + "version": "1.0.2", + "bundled": true + } + } + }, "fstream": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.11.tgz", @@ -8339,9 +9012,9 @@ "integrity": "sha1-JKwXdDPkou6REP5DWAutBZ+gBQk=" }, "office-ui-fabric-react": { - "version": "4.33.0", - "resolved": "https://registry.npmjs.org/office-ui-fabric-react/-/office-ui-fabric-react-4.33.0.tgz", - "integrity": "sha512-wgPdX4jU+GFcselCpEtSAfBnyDzVH0Hg5WnVhW08XUQM9nuT92DKfVoxq3BfL/6164DG7yIbVVTzfgD2aJWjGw==" + "version": "4.34.0", + "resolved": "https://registry.npmjs.org/office-ui-fabric-react/-/office-ui-fabric-react-4.34.0.tgz", + "integrity": "sha512-23twEIf81GH6qro92oAve7ZG1MVDxBgtOuKR3Rq3e/Z/LIGF/OWGRyetmHe0+k9Tpzw7sLUud+3KG7IEZ98LSg==" }, "on-finished": { "version": "2.3.0", @@ -9400,9 +10073,9 @@ "integrity": "sha1-VNvzd+UUQKypCkzSdGANP/LYiKk=" }, "remove-trailing-separator": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.0.2.tgz", - "integrity": "sha1-abBi2XhyetFNxrVrpKt3L9jXBRE=" + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", + "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=" }, "repeat-element": { "version": "1.1.2", @@ -11523,4 +12196,4 @@ "integrity": "sha1-RCs4+denr3rke/z8NWhz6GFq0bc=" } } -} \ No newline at end of file +} diff --git a/packages/example-app-base/package.json b/packages/example-app-base/package.json index 8b646ce04b9465..d8c11efffa3263 100644 --- a/packages/example-app-base/package.json +++ b/packages/example-app-base/package.json @@ -30,14 +30,14 @@ "enzyme": "^2.7.0", "es6-promise": "^4.1.0", "gulp": "~3.9.1", - "mocha": "~3.3.0", + "mocha": "^3.3.0", "office-ui-fabric-react-tslint": ">=1.0.0 <2.0.0", "react": "^15.4.2", "react-addons-test-utils": "^15.4.2", "react-dom": "^15.4.2", "sass-loader": "^6.0.3", "style-loader": "^0.17.0", - "source-map-loader": "0.2.1", + "source-map-loader": "^0.2.1", "ts-loader": "^2.1.0", "typescript": "2.4.2", "webpack-dev-server": "^2.4.1", diff --git a/packages/experiments/package.json b/packages/experiments/package.json index fad1f0a6580357..83e5c54492b436 100644 --- a/packages/experiments/package.json +++ b/packages/experiments/package.json @@ -41,7 +41,7 @@ "gutil": "1.6.4", "highlight.js": "^9.6.0", "load-themed-styles-loader": "^0.0.3", - "mocha": "^3.2.0", + "mocha": "^3.3.0", "mocha-loader": "^1.1.1", "node-sass": "^4.5.0", "office-ui-fabric-react-tslint": ">=1.0.0 <2.0.0", @@ -53,7 +53,7 @@ "react-highlight": "0.9.0", "sass-loader": "^6.0.3", "sinon": "^2.3.2", - "source-map-loader": "0.2.1", + "source-map-loader": "^0.2.1", "style-loader": "^0.17.0", "ts-loader": "^2.0.1", "typescript": "2.4.2", diff --git a/packages/merge-styles/.npmignore b/packages/merge-styles/.npmignore new file mode 100644 index 00000000000000..b632939d809a6f --- /dev/null +++ b/packages/merge-styles/.npmignore @@ -0,0 +1,22 @@ +*.config.js +*.nuspec +*.yml +*.test.* +.editorconfig +.gitattributes +.gitignore +.vscode +coverage +dist/*.stats.html +dist/demo*.* +gulpfile.js +index.html +jsconfig.json +karma.config.js +node_modules +src +tsconfig.json +tsd.json +tslint.json +typings +webpack.config.js diff --git a/packages/merge-styles/.npmrc b/packages/merge-styles/.npmrc new file mode 100644 index 00000000000000..825c83e09df4da --- /dev/null +++ b/packages/merge-styles/.npmrc @@ -0,0 +1,2 @@ +registry=https://registry.npmjs.org/ + diff --git a/packages/merge-styles/LICENSE b/packages/merge-styles/LICENSE new file mode 100644 index 00000000000000..310f6231e35c59 --- /dev/null +++ b/packages/merge-styles/LICENSE @@ -0,0 +1,15 @@ +Office UI Fabric React - merge-styles + +Copyright (c) Microsoft Corporation + +All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Note: Usage of the fonts and icons referenced in Office UI Fabric is subject to the terms listed at http://aka.ms/fabric-assets-license \ No newline at end of file diff --git a/packages/merge-styles/README.md b/packages/merge-styles/README.md new file mode 100644 index 00000000000000..c8c01d896341f2 --- /dev/null +++ b/packages/merge-styles/README.md @@ -0,0 +1,225 @@ +# [Office UI Fabric - merge-styles](http://dev.office.com/fabric) + +The merge-styles library provides a number of utilities for loading styles through javascript. It is designed to make it simple to convert javascript style objects into css classes on the fly. + +The basic idea is to provide a method which can take in one or more style objects css styling javascript objects representing the styles for a given element, and return a single class name. If the same set of styling is passed in, the same name returns and nothing is re-registered. + +This has a number of benefits over traditional build time staticly produced css: + +* Only register classes that are needed, when they're needed, reducing the overall selector count. + +* Dynamically create new class permutations based on contextual theming requirements. (Use a different theme inside of a DIV without downloading multiple copies of the css rule definitions.) + +* Use JavaScript to define the class content (using utilities like color converters, or reusing constant numbers becomes possible.) + +* Allow control libraries to merge customized styling in with their rules, avoiding complexities like css selector specificity. + +* Simplify RTL processing; lefts become rights in RTL, in the actual rules. No complexity like `html[dir=rtl]` prefixes necessary, which alleviates unexpected specificity bugs. + +* Reduce bundle size. Automatically handles vendor prefixing, unit providing, RTL flipping, and margin/padding expansion (e.g. margin will automatically expand out to margin TRBL, so that we avoid specificity problems when merging things together.) + +* Reduce the build time overhead of running through CSS preprocessors. + +* TypeScript type safety; spell "background" wrong and get build breaks. + +The api surfaces consists of TypeScript interfaces and a few important methods: + +`mergeStyles(..args[]` - Takes in one or more style objects, merges them in the right order, and produces a single css class name which can be injected into any component. + +`mergeStyleSet` - Takes in one or more style set objects, each consisting of a set of areas, each which will produce a class name. Using this is analogous to calling mergeStyles for each property in the object, but ensures we maintain the set ordering when multiple style sets are merged. + +`concatStyleSet` - In some cases you simply need to combine style sets, without actually generating class names (it is costs in performance to generate class names.) This tool returns a single set merging many together. + +## Vocabulary + +Let's clear up a few definitions before we start; + +A *style object* represents the collection of css rules, except that the names are camelCased rather than kebab-cased. Example: + +```tsx +let style = { + backgroundColor: 'red', + left: 42 +}; +``` + +Additionally, *style objects* can contain selectors under the `selectors` property: + +```tsx +let style = { + backgroundColor: 'red', + selectors: { + ':hover': { + backgroundColor: 'blue'; + }, + '.parent &': { /* parent selector */ }, + '& .child': { /* child selector */ } + } +}; +``` + +A *style set* represents a map of area to style object. When building a component, you need to generate a class name for each element that requires styling. You would defint this in a *style set*. + +```tsx +let styleSet = { + root: { background: 'red' }, + button: { margin: 42 } +} +``` + +## Basic usage + +When building a component, you will need a *style set* map of class names to inject into your elements' class attributes. + +The recommended pattern is to provide the classnames in a separate function, typically in a separate file `ComponentName.classNames.ts`. + +```tsx +import { IStyle, mergeStyleSets, memoize } from '@uifabric/merge-styles'; + +export interface IComponentClassNames { + root: string; + button: string; + buttonIcon: string; +} + +export const getClassNames = () => { + return mergeStyleSets({ + root: { + background: 'red' + } + ), + + button: { + backgroundColor: 'green', + selectors: { + ':hover': { + backgroundColor: 'blue' + } + } + }, + + buttonIcon: { + margin: 10 + } + }); +}; +``` + +The class map can then be used in a component: + +```tsx +import { getClassNames } from './MyComponent.classNames'; + +export const MyComponent = () => { + let { root, button, buttonIcon } = getClassNames(); + + return ( +
+ +
+ ); +}; +``` + +## Managing conditionals and states + +Style objects can be represented by a simple object, but also can be an array of the objects. The merge functions will handle arrays and merge things together in the given order. They will also ignore falsey values, allowing you to conditionalize the results. + +In the following example, the root class generated will be different depending on the `isToggled` state: + +```tsx +export const getClassNames = ( + isToggled: boolean +): IComponentClassNames => { + + return mergeStyleSet({ + root: [ + { + background: 'red' + }, + isToggled && { + background: 'green' + } + ] + }) +}; +``` + +## Optimizing for performance + +Resolving the class names on every render can be an unwanted expense especially in hot spots where things are rendered frequently. To optimize, we recommend 2 guidelines: + +1. For your `getClassNames` function, flatten all input parameters into simple immutable values. This helps the `memoize` utility to cache the results based on the input. + +2. Use the `memoize` function from the `@uifabric/utilities` package to cache the results, given a unique combination of inputs. Example: + +```tsx +import { memoize } from '@uifabric/utilities'; + +export const getClassNames = memoize(( + isToggled: boolean +) => { + return mergeStyleSet({ + // ... + }); +}); +``` + +## Registering fonts + +Registering font faces example: + +```tsx +import { fontFace } from '@uifabric/merge-styles'; + +fontFace({ + fontFamily: `"Segoe UI"`, + src: `url("//cdn.com/fontface.woff2) format(woff2)`, + fontWeight: "normal" +}); +``` + +Note that in cases like `fontFamily` you may need to embed quotes in the string as shown above. + +## Registering keyframes + +Registering animation keyframes example: + +```tsx +import { keyframes, mergeStyleSets } from '@uifabric/merge-styles'; + +let fadeIn = keyframes({ + "from": { + opacity: 0 + }, + "to": { + opacity: 1 + } +}); + +export const getClassNames = () => { + return mergeStyleSets({ + root: { + animationName: fadeIn + } + }); +}; +``` + +## Server-side rendering + +Example: + +```tsx +import { renderStatic } from '@uifabric/merge-styles/lib/server'; + +let { html, css } = renderStatic(() => { + return ReactDOM.renderToString(...); +}); +``` + +Caveats: + +* Currently font face definitions and keyframes won't be included in the result. diff --git a/packages/merge-styles/api/merge-styles.api.ts b/packages/merge-styles/api/merge-styles.api.ts new file mode 100644 index 00000000000000..5e49a39a899887 --- /dev/null +++ b/packages/merge-styles/api/merge-styles.api.ts @@ -0,0 +1,366 @@ +// @public +export function concatStyleSets < T extends {} >(...args: (T | false | null | undefined)[]): T; + +// @public +export function fontFace(font: IFontFace): void; + +// @public +interface IExtendedRawStyle extends IRawStyle { + // (undocumented) + displayName?: string; + // (undocumented) + selectors?: { + [ key: string ]: IStyle; + } +} + +// @public (undocumented) +interface IFontFace extends IRawFontStyle { + // (undocumented) + fontFeatureSettings?: string; + src?: string; + unicodeRange?: ICSSRule | string; +} + +// @public (undocumented) +interface IRawStyle extends IRawFontStyle { + alignContent?: ICSSRule | 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around' | 'stretch'; + alignItems?: ICSSRule | 'flex-start' | 'flex-end' | 'center' | 'baseline' | 'stretch'; + alignmentAdjust?: ICSSRule | string; + // (undocumented) + alignmentBaseline?: ICSSRule | string; + alignSelf?: ICSSRule | 'auto' | 'flex-start' | 'flex-end' | 'center' | 'baseline' | 'stretch'; + animationDelay?: ICSSRule | string; + animationDirection?: ICSSRule | string; + animationDuration?: ICSSRule | string; + // (undocumented) + animationFillMode?: ICSSRule | 'none' | 'forwards' | 'backwards' | 'both'; + animationIterationCount?: ICSSRule | string; + animationName?: ICSSRule | string; + animationPlayState?: ICSSRule | string; + animationTimingFunction?: ICSSRule | string; + appearance?: ICSSRule | string; + backfaceVisibility?: ICSSRule | string; + background?: ICSSRule | string; + backgroundAttachment?: ICSSRule | 'scroll' | 'fixed' | 'local'; + backgroundBlendMode?: ICSSRule | string; + backgroundColor?: ICSSRule | string; + // (undocumented) + backgroundComposite?: ICSSRule | string; + backgroundImage?: ICSSRule | string; + backgroundOrigin?: ICSSRule | string; + backgroundPosition?: ICSSRule | string; + backgroundRepeat?: ICSSRule | string; + baselineShift?: ICSSRule | string; + behavior?: ICSSRule | string; + border?: ICSSRule | 0 | string; + borderBottom?: ICSSRule | number | string; + borderBottomColor?: ICSSRule | string; + borderBottomLeftRadius?: ICSSRule | string; + borderBottomRightRadius?: ICSSRule | string; + borderBottomStyle?: ICSSRule | string; + borderBottomWidth?: ICSSRule | string; + borderCollapse?: ICSSRule | string; + borderColor?: ICSSRule | string; + borderCornerShape?: ICSSRule | string; + borderImageSource?: ICSSRule | string; + borderImageWidth?: ICSSRule | string; + borderLeft?: ICSSRule | number | string; + borderLeftColor?: ICSSRule | string; + borderLeftStyle?: ICSSRule | string; + borderLeftWidth?: ICSSRule | string; + borderRadius?: ICSSRule | string; + borderRight?: ICSSRule | number | string; + borderRightColor?: ICSSRule | string; + borderRightStyle?: ICSSRule | string; + borderRightWidth?: ICSSRule | string; + borderSpacing?: ICSSRule | string; + borderStyle?: ICSSRule | string; + borderTop?: ICSSRule | number | string; + borderTopColor?: ICSSRule | string; + borderTopLeftRadius?: ICSSRule | string; + borderTopRightRadius?: ICSSRule | string; + borderTopStyle?: ICSSRule | string; + borderTopWidth?: ICSSRule | string; + borderWidth?: ICSSRule | number | string; + bottom?: ICSSRule | number | string; + // (undocumented) + boxAlign?: ICSSRule | string; + boxDecorationBreak?: ICSSRule | string; + // (undocumented) + boxDirection?: ICSSRule | string; + boxFlex?: ICSSRule | number; + boxFlexGroup?: ICSSRule | number; + boxLineProgression?: ICSSRule | string; + boxLines?: ICSSRule | string; + boxOrdinalGroup?: ICSSRule | string; + boxShadow?: ICSSRule | string; + boxSizing?: ICSSRule | 'border-box' | 'content-box'; + breakAfter?: ICSSRule | string; + breakBefore?: ICSSRule | string; + breakInside?: ICSSRule | string; + clear?: ICSSRule | string; + clip?: ICSSRule | string; + clipRule?: ICSSRule | string; + color?: ICSSRule | string; + columnCount?: ICSSRule | number | 'auto'; + columnFill?: ICSSRule | string; + columnGap?: ICSSRule | string; + columnRule?: ICSSRule | string; + columnRuleColor?: ICSSRule | string; + columnRuleWidth?: ICSSRule | string; + columns?: ICSSRule | string; + columnSpan?: ICSSRule | string; + columnWidth?: ICSSRule | string; + content?: string; + counterIncrement?: ICSSRule | string; + counterReset?: ICSSRule | string; + cue?: ICSSRule | string; + cueAfter?: ICSSRule | string; + cursor?: ICSSRule | string; + direction?: ICSSRule | string; + display?: ICSSRule | string; + fill?: ICSSRule | string; + fillOpacity?: ICSSRule | number; + fillRule?: ICSSRule | string; + filter?: ICSSRule | string; + flex?: ICSSRule | number | string; + flexAlign?: ICSSRule | string; + flexBasis?: ICSSRule | string; + flexDirection?: ICSSRule | 'row' | 'row-reverse' | 'column' | 'column-reverse'; + flexFlow?: ICSSRule | string; + flexGrow?: ICSSRule | number; + flexItemAlign?: ICSSRule | string; + flexLinePack?: ICSSRule | string; + flexOrder?: ICSSRule | string; + flexShrink?: ICSSRule | number; + flexWrap?: ICSSRule | 'nowrap' | 'wrap' | 'wrap-reverse'; + float?: ICSSRule | string; + flowFrom?: ICSSRule | string; + gridArea?: ICSSRule | string; + gridColumn?: ICSSRule | string; + gridColumnEnd?: ICSSRule | string; + gridColumnStart?: ICSSRule | string; + gridRow?: ICSSRule | string; + gridRowEnd?: ICSSRule | string; + gridRowPosition?: ICSSRule | string; + // (undocumented) + gridRowSpan?: ICSSRule | string; + gridTemplateAreas?: ICSSRule | string; + gridTemplateColumns?: ICSSRule | string; + gridTemplateRows?: ICSSRule | string; + height?: ICSSRule | string; + hyphenateLimitChars?: ICSSRule | string; + hyphenateLimitLines?: ICSSRule | string; + hyphenateLimitZone?: ICSSRule | string; + hyphens?: ICSSRule | string; + // (undocumented) + imeMode?: ICSSRule | string; + justifyContent?: ICSSRule | 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around' | 'space-evenly'; + // (undocumented) + layoutGrid?: ICSSRule | string; + // (undocumented) + layoutGridChar?: ICSSRule | string; + // (undocumented) + layoutGridLine?: ICSSRule | string; + // (undocumented) + layoutGridMode?: ICSSRule | string; + // (undocumented) + layoutGridType?: ICSSRule | string; + left?: ICSSRule | number | string; + letterSpacing?: ICSSRule | string; + lineBreak?: ICSSRule | string; + // (undocumented) + lineClamp?: ICSSRule | number; + lineHeight?: ICSSRule | 'normal' | number | ICSSLengthRule | ICSSPercentageRule; + listStyle?: ICSSRule | string; + listStyleImage?: ICSSRule | string; + listStylePosition?: ICSSRule | string; + listStyleType?: ICSSRule | string; + margin?: ICSSRule | number | string; + marginBottom?: ICSSRule | number | string; + marginLeft?: ICSSRule | number | string; + marginRight?: ICSSRule | number | string; + marginTop?: ICSSRule | number | string; + marqueeDirection?: ICSSRule | string; + marqueeStyle?: ICSSRule | string; + mask?: ICSSRule | string; + maskBorder?: ICSSRule | string; + maskBorderRepeat?: ICSSRule | string; + maskBorderSlice?: ICSSRule | string; + maskBorderSource?: ICSSRule | string; + maskBorderWidth?: ICSSRule | string; + maskClip?: ICSSRule | string; + maskOrigin?: ICSSRule | string; + maxFontSize?: ICSSRule | string; + maxHeight?: ICSSRule | string; + maxWidth?: ICSSRule | string; + minHeight?: ICSSRule | string; + minWidth?: ICSSRule | string; + MozFontSmoothing?: string; + opacity?: ICSSRule | number; + order?: ICSSRule | number; + orphans?: ICSSRule | number; + outline?: ICSSRule | 0 | string; + outlineColor?: ICSSRule | string; + outlineOffset?: ICSSRule | string; + overflow?: ICSSRule | 'auto' | 'hidden' | 'scroll' | 'visible'; + overflowStyle?: ICSSRule | string; + overflowWrap?: ICSSRule | 'normal' | 'break-word'; + overflowX?: ICSSRule | 'auto' | 'hidden' | 'scroll' | 'visible'; + overflowY?: ICSSRule | 'auto' | 'hidden' | 'scroll' | 'visible'; + padding?: ICSSRule | number | string; + paddingBottom?: ICSSRule | number | string; + paddingLeft?: ICSSRule | number | string; + paddingRight?: ICSSRule | number | string; + paddingTop?: ICSSRule | number | string; + pageBreakAfter?: ICSSRule | string; + pageBreakBefore?: ICSSRule | string; + pageBreakInside?: ICSSRule | string; + pause?: ICSSRule | string; + pauseAfter?: ICSSRule | string; + pauseBefore?: ICSSRule | string; + perspective?: ICSSRule | string; + perspectiveOrigin?: ICSSRule | string; + pointerEvents?: ICSSRule | string; + position?: ICSSRule | 'static' | 'relative' | 'absolute' | 'fixed' | 'sticky'; + punctuationTrim?: ICSSRule | string; + quotes?: ICSSRule | string; + regionFragment?: ICSSRule | string; + restAfter?: ICSSRule | string; + restBefore?: ICSSRule | string; + right?: ICSSRule | number | string; + // (undocumented) + rubyAlign?: ICSSRule | string; + // (undocumented) + rubyPosition?: ICSSRule | string; + shapeImageThreshold?: ICSSRule | string; + shapeInside?: ICSSRule | string; + shapeMargin?: ICSSRule | string; + shapeOutside?: ICSSRule | string; + speak?: ICSSRule | string; + speakAs?: ICSSRule | string; + strokeOpacity?: ICSSRule | number; + strokeWidth?: ICSSRule | ICSSPercentageRule | ICSSLengthRule; + tableLayout?: ICSSRule | string; + tabSize?: ICSSRule | string; + textAlign?: ICSSRule | string; + textAlignLast?: ICSSRule | string; + textDecoration?: ICSSRule | string; + textDecorationColor?: ICSSRule | string; + textDecorationLine?: ICSSRule | string; + // (undocumented) + textDecorationLineThrough?: ICSSRule | string; + // (undocumented) + textDecorationNone?: ICSSRule | string; + // (undocumented) + textDecorationOverline?: ICSSRule | string; + textDecorationSkip?: ICSSRule | string; + textDecorationStyle?: ICSSRule | string; + // (undocumented) + textDecorationUnderline?: ICSSRule | string; + textEmphasis?: ICSSRule | string; + textEmphasisColor?: ICSSRule | string; + textEmphasisStyle?: ICSSRule | string; + textHeight?: ICSSRule | string; + textIndent?: ICSSRule | string; + // (undocumented) + textJustifyTrim?: ICSSRule | string; + // (undocumented) + textKashidaSpace?: ICSSRule | string; + textLineThrough?: ICSSRule | string; + textLineThroughColor?: ICSSRule | string; + textLineThroughMode?: ICSSRule | string; + textLineThroughStyle?: ICSSRule | string; + textLineThroughWidth?: ICSSRule | string; + textOverflow?: ICSSRule | string; + textOverline?: ICSSRule | string; + textOverlineColor?: ICSSRule | string; + textOverlineMode?: ICSSRule | string; + textOverlineStyle?: ICSSRule | string; + textOverlineWidth?: ICSSRule | string; + textRendering?: ICSSRule | string; + textScript?: ICSSRule | string; + textShadow?: ICSSRule | string; + textTransform?: ICSSRule | string; + textUnderlinePosition?: ICSSRule | string; + textUnderlineStyle?: ICSSRule | string; + top?: ICSSRule | number | string; + touchAction?: ICSSRule | string; + transform?: ICSSRule | string; + transformOrigin?: ICSSRule | string; + transformOriginZ?: ICSSRule | string; + transformStyle?: ICSSRule | string; + transition?: ICSSRule | string; + transitionDelay?: ICSSRule | string; + transitionDuration?: ICSSRule | string; + transitionProperty?: ICSSRule | string; + transitionTimingFunction?: ICSSRule | string; + unicodeBidi?: ICSSRule | string; + userFocus?: ICSSRule | string; + userInput?: ICSSRule | string; + userSelect?: ICSSRule | 'none' | 'auto' | 'text' | 'all' | 'contain'; + verticalAlign?: ICSSRule | string; + visibility?: ICSSRule | string; + voiceBalance?: ICSSRule | string; + voiceDuration?: ICSSRule | string; + voiceFamily?: ICSSRule | string; + voicePitch?: ICSSRule | string; + voiceRange?: ICSSRule | string; + voiceRate?: ICSSRule | string; + voiceStress?: ICSSRule | string; + voiceVolume?: ICSSRule | string; + WebkitFontSmoothing?: 'none' | 'antialiased' | 'grayscale' | 'subpixel-antialiased'; + whiteSpace?: ICSSRule | string; + whiteSpaceTreatment?: ICSSRule | string; + widows?: ICSSRule | number; + width?: ICSSRule | string; + wordBreak?: ICSSRule | string; + wordSpacing?: ICSSRule | string; + wordWrap?: ICSSRule | string; + wrapFlow?: ICSSRule | string; + wrapMargin?: ICSSRule | string; + wrapOption?: ICSSRule | string; + writingMode?: ICSSRule | string; + zIndex?: ICSSRule | 'auto' | number; + zoom?: ICSSRule | 'auto' | number | ICSSPercentageRule; +} + +// @public (undocumented) +export function keyframes(timeline: { [key: string]: {} }): string; + +// @public +export function mergeStyles(...args: (IStyle | IStyle[])[]): string; + +// @public +export function mergeStyleSets < T extends {} >(...cssSets: T[]): {[P in keyof T]?: string }; + +// @public (undocumented) +class Stylesheet { + // WARNING: The type "IStyleSheetConfig" needs to be exported by the package (e.g. added to index.ts) + constructor(config?: IStyleSheetConfig); + // (undocumented) + public argsFromClassName(className: string): IStyle[] | undefined; + // (undocumented) + public cacheClassName(className: string, key: string, args: IStyle[]): void; + // (undocumented) + public classNameFromKey(key: string): string | undefined; + // (undocumented) + public getClassName(displayName?: string): string; + // (undocumented) + public static getInstance(): Stylesheet; + // (undocumented) + public getRules(): string; + // (undocumented) + public insertRule(rule: string, + forceSync: boolean = false): void; + // (undocumented) + public reset(): void; + // WARNING: The type "IStyleSheetConfig" needs to be exported by the package (e.g. added to index.ts) + // (undocumented) + public setConfig(config?: IStyleSheetConfig): void; +} + +// WARNING: Unsupported export: IStyle +// WARNING: Unsupported export: IFontWeight +// (No packageDescription for this package) diff --git a/packages/merge-styles/config/api-extractor.json b/packages/merge-styles/config/api-extractor.json new file mode 100644 index 00000000000000..9c294e8c13388f --- /dev/null +++ b/packages/merge-styles/config/api-extractor.json @@ -0,0 +1,6 @@ +{ + "enabled": true, + "apiReviewFolder": "./api", + "apiJsonFolder": "./temp", + "entry": "src/index.ts" +} \ No newline at end of file diff --git a/packages/merge-styles/gulpfile.js b/packages/merge-styles/gulpfile.js new file mode 100644 index 00000000000000..b5238c40e78a04 --- /dev/null +++ b/packages/merge-styles/gulpfile.js @@ -0,0 +1,45 @@ +'use strict'; + +let gulp = require('gulp'); +let path = require('path'); +let build = require('@microsoft/web-library-build'); +let buildConfig = build.getConfig(); + +let isProduction = process.argv.indexOf('--production') >= 0; +let isClean = process.argv.indexOf('clean') >= 0; + +// initialize tasks. +build.initialize(gulp); + +/* Configure lint rules */ +let rules = Object.assign( + {}, + require('./node_modules/@microsoft/gulp-core-build-typescript/lib/defaultTslint.json').rules, + require('./node_modules/office-ui-fabric-react-tslint/tslint.json').rules, + require('./tslint.json').rules +); +build.tslint.setConfig({ + lintConfig: { rules }, + displayAsWarning: false +}); + +// Configure TypeScript. +build.TypeScriptConfiguration.setTypescriptCompiler(require('typescript')); + +// Use css modules. +build.sass.setConfig({ useCSSModules: true }); + +/** Disable webpack. */ +build.webpack.isEnabled = () => false; + +let packageFolder = buildConfig.packageFolder || ''; +let distFolder = buildConfig.distFolder; + +if (isProduction || isClean) { + build.setConfig({ + libAMDFolder: path.join(packageFolder, 'lib-amd') + }); +} + +build.task('tslint', build.tslint); + diff --git a/packages/merge-styles/karma.config.js b/packages/merge-styles/karma.config.js new file mode 100644 index 00000000000000..a706b978e87418 --- /dev/null +++ b/packages/merge-styles/karma.config.js @@ -0,0 +1,111 @@ +'use strict'; + +// Karma configuration +// Generated on Thu Oct 08 2015 18:13:05 GMT-0700 (PDT) + +let path = require('path'); +let build = require('@microsoft/web-library-build'); +let buildConfig = build.getConfig(); +let configResources = build.karma.resources; +let bindPolyfillPath = configResources.bindPolyfillPath; +let debugRun = (process.argv.indexOf('--debug') > -1); + +module.exports = function (config) { + let karmaConfig = { + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '.', + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'sinon-chai'], + + + // list of files / patterns to load in the browser + files: [bindPolyfillPath].concat([path.join(buildConfig.libFolder, '**', '*.test.js')]), + + + // list of files to exclude + exclude: [], + + + // webpack config for bundling tests. + webpack: { + devtool: 'source-map', + module: { + loaders: [ + { + test: /sinon\.js$/, + loader: 'imports?define=>false', + enforce: 'pre' + }, + debugRun ? {} : { + test: /\.js/, + exclude: /(test|node_modules|bower_components)/, + loader: configResources.istanbulInstrumenterLoaderPath, + enforce: 'post' + } + ], + }, + externals: { + 'cheerio': 'window', + 'react/addons': true, + 'react/lib/ExecutionEnvironment': true, + 'react/lib/ReactContext': true + }, + resolve: { + modules: [ + buildConfig.libFolder, + 'node_modules' + ] + } + }, + + webpackMiddleware: { + noInfo: true + }, + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + [path.join(buildConfig.libFolder, '/**/*.js')]: ['webpack'] + }, + + plugins: configResources.plugins.concat([ + ]), + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['mocha-clean', 'coverage'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: false, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: true + }; + + config.set(karmaConfig); +}; diff --git a/packages/merge-styles/package.json b/packages/merge-styles/package.json new file mode 100644 index 00000000000000..d07ab8861974c7 --- /dev/null +++ b/packages/merge-styles/package.json @@ -0,0 +1,54 @@ +{ + "name": "@uifabric/merge-styles", + "version": "4.9.0", + "description": "Office UI Fabric style loading utilities.", + "main": "lib/index.js", + "typings": "lib/index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/OfficeDev/office-ui-fabric-react" + }, + "license": "MIT", + "scripts": { + "build": "gulp", + "clean": "gulp clean", + "test": "gulp", + "start": "node node_modules/webpack-dev-server/bin/webpack-dev-server.js" + }, + "devDependencies": { + "@microsoft/web-library-build": "^3.2.1", + "@types/chai": "3.4.35", + "@types/enzyme": "2.8.0", + "@types/es6-promise": "^0.0.32", + "@types/es6-weak-map": "1.2.0", + "@types/mocha": "2.2.39", + "@types/prop-types": "15.5.1", + "@types/react": "15.0.38", + "@types/react-addons-test-utils": "0.14.18", + "@types/react-dom": "15.5.1", + "@types/sinon": "2.2.2", + "@types/webpack-env": "1.13.0", + "enzyme": "^2.7.0", + "es6-map": "^0.1.5", + "es6-promise": "^4.1.0", + "es6-weak-map": "^2.0.2", + "gulp": "~3.9.1", + "mocha": "^3.3.0", + "office-ui-fabric-react-tslint": ">=1.0.0 <2.0.0", + "react": "^15.4.2", + "react-addons-test-utils": "^15.4.2", + "react-dom": "^15.4.2", + "sinon": "^2.3.2", + "source-map-loader": "^0.2.1", + "typescript": "2.4.2" + }, + "dependencies": { + "@uifabric/utilities": ">=4.9.0 <5.0.0", + "prop-types": "^15.5.10", + "tslib": "^1.6.0" + }, + "peerDependencies": { + "react": "^0.14.9 || ^15.0.1-0 || ^16.0.0-0", + "react-dom": "^0.14.9 || ^15.0.1-0 || ^16.0.0-0" + } +} \ No newline at end of file diff --git a/packages/merge-styles/src/IRawStyle.ts b/packages/merge-styles/src/IRawStyle.ts new file mode 100644 index 00000000000000..8e88369ba63574 --- /dev/null +++ b/packages/merge-styles/src/IRawStyle.ts @@ -0,0 +1,1916 @@ +// See CSS 3 CSS-wide keywords https://www.w3.org/TR/css3-values/#common-keywords +// See CSS 3 Explicit Defaulting https://www.w3.org/TR/css-cascade-3/#defaulting-keywords +// "all CSS properties can accept these values" +export type ICSSRule = 'initial' | 'inherit' | 'unset'; + +// See CSS 3 type https://drafts.csswg.org/css-values-3/#percentages +export type ICSSPercentageRule = string; + +// See CSS 3 type https://drafts.csswg.org/css-values-3/#lengths +export type ICSSLengthRule = number | string; + +export type IFontWeight = ICSSRule | 'normal' | 'bold' | 'bolder' | 'lighter' | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; + +export interface IRawFontStyle { + /** + * The font property is shorthand that allows you to do one of two things: you can + * either set up six of the most mature font properties in one line, or you can set + * one of a choice of keywords to adopt a system font setting. + */ + font?: ICSSRule | string; + + /** + * The font-family property allows one or more font family names and/or generic family + * names to be specified for usage on the selected element(s)' text. The browser then + * goes through the list; for each character in the selection it applies the first + * font family that has an available glyph for that character. + */ + fontFamily?: ICSSRule | string; + + /** + * The font-kerning property allows contextual adjustment of inter-glyph spacing, i.e. + * the spaces between the characters in text. This property controls metric + * kerning - that utilizes adjustment data contained in the font. Optical + * Kerning is not supported as yet. + */ + fontKerning?: ICSSRule | string; + + /** + * Specifies the size of the font. Used to compute em and ex units. + * See CSS 3 font-size property https://www.w3.org/TR/css-fonts-3/#propdef-font-size + */ + fontSize?: + | ICSSRule + | 'xx-small' + | 'x-small' + | 'small' + | 'medium' + | 'large' + | 'x-large' + | 'xx-large' + | 'larger' + | 'smaller' + | ICSSLengthRule + | ICSSPercentageRule; + + /** + * The font-size-adjust property adjusts the font-size of the fallback fonts defined + * with font-family, so that the x-height is the same no matter what font is used. + * This preserves the readability of the text when fallback happens. + * See CSS 3 font-size-adjust property + * https://www.w3.org/TR/css-fonts-3/#propdef-font-size-adjust + */ + fontSizeAdjust?: ICSSRule | 'none' | number; + + /** + * Allows you to expand or condense the widths for a normal, condensed, or expanded + * font face. + * See CSS 3 font-stretch property + * https://drafts.csswg.org/css-fonts-3/#propdef-font-stretch + */ + fontStretch?: + | ICSSRule + | 'normal' + | 'ultra-condensed' + | 'extra-condensed' + | 'condensed' + | 'semi-condensed' + | 'semi-expanded' + | 'expanded' + | 'extra-expanded' + | 'ultra-expanded'; + + /** + * The font-style property allows normal, italic, or oblique faces to be selected. + * Italic forms are generally cursive in nature while oblique faces are typically + * sloped versions of the regular face. Oblique faces can be simulated by artificially + * sloping the glyphs of the regular face. + * See CSS 3 font-style property https://www.w3.org/TR/css-fonts-3/#propdef-font-style + */ + fontStyle?: ICSSRule | 'normal' | 'italic' | 'oblique'; + + /** + * This value specifies whether the user agent is allowed to synthesize bold or + * oblique font faces when a font family lacks bold or italic faces. + */ + fontSynthesis?: ICSSRule | string; + + /** + * The font-variant property enables you to select the small-caps font within a font + * family. + */ + fontVariant?: ICSSRule | string; + + /** + * Fonts can provide alternate glyphs in addition to default glyph for a character. + * This property provides control over the selection of these alternate glyphs. + */ + fontVariantAlternates?: ICSSRule | string; + + /** + * Specifies the weight or boldness of the font. + * See CSS 3 'font-weight' property https://www.w3.org/TR/css-fonts-3/#propdef-font-weight + */ + fontWeight?: IFontWeight; +} + +/** + * @public + */ +export interface IFontFace extends IRawFontStyle { + /** + * Specifies the src of the font. + */ + src?: string; + + /** + * unicode-range allows you to set a specific range of characters to be downloaded + * from a font (embedded using @font-face) and made available for use on the current + * page. + */ + unicodeRange?: ICSSRule | string; + + fontFeatureSettings?: string; +} + +/** + * @public + */ +export interface IRawStyle extends IRawFontStyle { + /** + * (Moz specific) font smoothing directive. + */ + MozFontSmoothing?: string; + + /** + * (Webkit specific) font smoothing directive. + */ + WebkitFontSmoothing?: 'none' | 'antialiased' | 'grayscale' | 'subpixel-antialiased'; + + /** + * Aligns a flex container's lines within the flex container when there is extra space + * in the cross-axis, similar to how justify-content aligns individual items within the main-axis. + */ + alignContent?: ICSSRule | 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around' | 'stretch'; + + /** + * Sets the default alignment in the cross axis for all of the flex container's items, + * including anonymous flex items, similarly to how justify-content aligns items along the main axis. + */ + alignItems?: ICSSRule | 'flex-start' | 'flex-end' | 'center' | 'baseline' | 'stretch'; + + /** + * Allows the default alignment to be overridden for individual flex items. + */ + alignSelf?: ICSSRule | 'auto' | 'flex-start' | 'flex-end' | 'center' | 'baseline' | 'stretch'; + + /** + * This property allows precise alignment of elements, such as graphics, that do not + * have a baseline-table or lack the desired baseline in their baseline-table. With the + * alignment-adjust property, the position of the baseline identified by the + * alignment-baseline can be explicitly determined. It also determines precisely + * the alignment point for each glyph within a textual element. + */ + alignmentAdjust?: ICSSRule | string; + + alignmentBaseline?: ICSSRule | string; + + /** + * Defines a length of time to elapse before an animation starts, allowing an animation to begin execution some time after it is applied. + */ + animationDelay?: ICSSRule | string; + + /** + * Defines whether an animation should run in reverse on some or all cycles. + */ + animationDirection?: ICSSRule | string; + + /** + * Specifies the length an animation takes to finish. Default value is 0, meaning + * there will be no animation. + */ + animationDuration?: ICSSRule | string; + + /** + * + */ + animationFillMode?: ICSSRule | 'none' | 'forwards' | 'backwards' | 'both'; + + /** + * Specifies how many times an animation cycle should play. + */ + animationIterationCount?: ICSSRule | string; + + /** + * Defines the list of animations that apply to the element. + */ + animationName?: ICSSRule | string; + + /** + * Defines whether an animation is running or paused. + */ + animationPlayState?: ICSSRule | string; + + /** + * The animation-timing-function specifies the speed curve of an animation. + */ + animationTimingFunction?: ICSSRule | string; + + /** + * Allows changing the style of any element to platform-based interface elements or + * vice versa. + */ + appearance?: ICSSRule | string; + + /** + * Determines whether or not the “back” side of a transformed element is visible when + * facing the viewer. + */ + backfaceVisibility?: ICSSRule | string; + + /** + * Shorthand property to set the values for one or more of: + * background-clip, background-color, background-image, + * background-origin, background-position, background-repeat, + * background-size, and background-attachment. + */ + background?: ICSSRule | string; + + /** + * If a background-image is specified, this property determines + * whether that image's position is fixed within the viewport, + * or scrolls along with its containing block. + * See CSS 3 background-attachment property https://drafts.csswg.org/css-backgrounds-3/#the-background-attachment + */ + backgroundAttachment?: ICSSRule | 'scroll' | 'fixed' | 'local'; + + /** + * This property describes how the element's background images should blend with each + * other and the element's background color. The value is a list of blend modes that + * corresponds to each background image. Each element in the list will apply to the + * corresponding element of background-image. If a property doesn’t have enough + * comma-separated values to match the number of layers, the UA must calculate its + * used value by repeating the list of values until there are enough. + */ + backgroundBlendMode?: ICSSRule | string; + + /** + * Sets the background color of an element. + */ + backgroundColor?: ICSSRule | string; + + backgroundComposite?: ICSSRule | string; + + /** + * Applies one or more background images to an element. These can be any valid CSS + * image, including url() paths to image files or CSS gradients. + */ + backgroundImage?: ICSSRule | string; + + /** + * Specifies what the background-position property is relative to. + */ + backgroundOrigin?: ICSSRule | string; + + /** + * Sets the position of a background image. + */ + backgroundPosition?: ICSSRule | string; + + /** + * Background-repeat defines if and how background images will be repeated after they + * have been sized and positioned + */ + backgroundRepeat?: ICSSRule | string; + + /** + * Obsolete - spec retired, not implemented. + */ + baselineShift?: ICSSRule | string; + + /** + * Non standard. Sets or retrieves the location of the Dynamic HTML (DHTML) behavior. + */ + behavior?: ICSSRule | string; + + /** + * Shorthand property that defines the different properties of all four sides of an + * element's border in a single declaration. It can be used to set border-width, + * border-style and border-color, or a subset of these. + */ + border?: ICSSRule | 0 | string; + + /** + * Shorthand that sets the values of border-bottom-color, + * border-bottom-style, and border-bottom-width. + */ + borderBottom?: ICSSRule | number | string; + + /** + * Sets the color of the bottom border of an element. + */ + borderBottomColor?: ICSSRule | string; + + /** + * Defines the shape of the border of the bottom-left corner. + */ + borderBottomLeftRadius?: ICSSRule | string; + + /** + * Defines the shape of the border of the bottom-right corner. + */ + borderBottomRightRadius?: ICSSRule | string; + + /** + * Sets the line style of the bottom border of a box. + */ + borderBottomStyle?: ICSSRule | string; + + /** + * Sets the width of an element's bottom border. To set all four borders, use the + * border-width shorthand property which sets the values simultaneously for + * border-top-width, border-right-width, border-bottom-width, and border-left-width. + */ + borderBottomWidth?: ICSSRule | string; + + /** + * Border-collapse can be used for collapsing the borders between table cells + */ + borderCollapse?: ICSSRule | string; + + /** + * The CSS border-color property sets the color of an element's four borders. This + * property can have from one to four values, made up of the elementary properties: + * • border-top-color + * • border-right-color + * • border-bottom-color + * • border-left-color The default color is the currentColor of each of + * these values. + * If you provide one value, it sets the color for the element. Two values set the + * horizontal and vertical values, respectively. Providing three values sets the top, + * vertical, and bottom values, in that order. Four values set all for sides: top, + * right, bottom, and left, in that order. + */ + borderColor?: ICSSRule | string; + + /** + * Specifies different corner clipping effects, such as scoop (inner curves), bevel + * (straight cuts) or notch (cut-off rectangles). Works along with border-radius to + * specify the size of each corner effect. + */ + borderCornerShape?: ICSSRule | string; + + /** + * The property border-image-source is used to set the image to be used instead of + * the border style. If this is set to none the border-style is used instead. + */ + borderImageSource?: ICSSRule | string; + + /** + * The border-image-width CSS property defines the offset to use for dividing the + * border image in nine parts, the top-left corner, central top edge, top-right-corner, + * central right edge, bottom-right corner, central bottom edge, bottom-left corner, + * and central right edge. They represent inward distance from the top, right, bottom, + * and left edges. + */ + borderImageWidth?: ICSSRule | string; + + /** + * Shorthand property that defines the border-width, border-style and border-color of + * an element's left border in a single declaration. Note that you can use the + * corresponding longhand properties to set specific individual properties of the left + * border — border-left-width, border-left-style and border-left-color. + */ + borderLeft?: ICSSRule | number | string; + + /** + * The CSS border-left-color property sets the color of an element's left border. This + * page explains the border-left-color value, but often you will find it more + * convenient to fix the border's left color as part of a shorthand set, either + * border-left or border-color. Colors can be defined several ways. For more + * information, see Usage. + */ + borderLeftColor?: ICSSRule | string; + + /** + * Sets the style of an element's left border. To set all four borders, use the + * shorthand property, border-style. Otherwise, you can set the borders individually + * with border-top-style, border-right-style, border-bottom-style, border-left-style. + */ + borderLeftStyle?: ICSSRule | string; + + /** + * Sets the width of an element's left border. To set all four borders, use the + * border-width shorthand property which sets the values simultaneously for + * border-top-width, border-right-width, border-bottom-width, and border-left-width. + */ + borderLeftWidth?: ICSSRule | string; + + /** + * Defines how round the border's corners are. + */ + borderRadius?: ICSSRule | string; + + /** + * Shorthand property that defines the border-width, border-style and border-color of + * an element's right border in a single declaration. Note that you can use the + * corresponding longhand properties to set specific individual properties of the + * right border — border-right-width, border-right-style and border-right-color. + */ + borderRight?: ICSSRule | number | string; + + /** + * Sets the color of an element's right border. This page explains the + * border-right-color value, but often you will find it more convenient to fix the + * border's right color as part of a shorthand set, either border-right or border-color. + * Colors can be defined several ways. For more information, see Usage. + */ + borderRightColor?: ICSSRule | string; + + /** + * Sets the style of an element's right border. To set all four borders, use the + * shorthand property, border-style. Otherwise, you can set the borders individually + * with border-top-style, border-right-style, border-bottom-style, border-left-style. + */ + borderRightStyle?: ICSSRule | string; + + /** + * Sets the width of an element's right border. To set all four borders, use the + * border-width shorthand property which sets the values simultaneously for + * border-top-width, border-right-width, border-bottom-width, and border-left-width. + */ + borderRightWidth?: ICSSRule | string; + + /** + * Specifies the distance between the borders of adjacent cells. + */ + borderSpacing?: ICSSRule | string; + + /** + * Sets the style of an element's four borders. This property can have from one to + * four values. With only one value, the value will be applied to all four borders; + * otherwise, this works as a shorthand property for each of border-top-style, + * border-right-style, border-bottom-style, border-left-style, where each border + * style may be assigned a separate value. + */ + borderStyle?: ICSSRule | string; + + /** + * Shorthand property that defines the border-width, border-style and border-color of + * an element's top border in a single declaration. Note that you can use the + * corresponding longhand properties to set specific individual properties of the top + * border — border-top-width, border-top-style and border-top-color. + */ + borderTop?: ICSSRule | number | string; + + /** + * Sets the color of an element's top border. This page explains the border-top-color + * value, but often you will find it more convenient to fix the border's top color as + * part of a shorthand set, either border-top or border-color. + * Colors can be defined several ways. For more information, see Usage. + */ + borderTopColor?: ICSSRule | string; + + /** + * Sets the rounding of the top-left corner of the element. + */ + borderTopLeftRadius?: ICSSRule | string; + + /** + * Sets the rounding of the top-right corner of the element. + */ + borderTopRightRadius?: ICSSRule | string; + + /** + * Sets the style of an element's top border. To set all four borders, use the + * shorthand property, border-style. Otherwise, you can set the borders individually + * with border-top-style, border-right-style, border-bottom-style, border-left-style. + */ + borderTopStyle?: ICSSRule | string; + + /** + * Sets the width of an element's top border. To set all four borders, use the + * border-width shorthand property which sets the values simultaneously for + * border-top-width, border-right-width, border-bottom-width, and border-left-width. + */ + borderTopWidth?: ICSSRule | string; + + /** + * Sets the width of an element's four borders. This property can have from one to + * four values. This is a shorthand property for setting values simultaneously for + * border-top-width, border-right-width, border-bottom-width, and border-left-width. + */ + borderWidth?: ICSSRule | number | string; + + /** + * This property specifies how far an absolutely positioned box's bottom margin edge + * is offset above the bottom edge of the box's containing block. For relatively + * positioned boxes, the offset is with respect to the bottom edges of the box itself + * (i.e., the box is given a position in the normal flow, then offset from that + * position according to these properties). + */ + bottom?: ICSSRule | number | string; + + /** + * Obsolete. + */ + boxAlign?: ICSSRule | string; + + /** + * Breaks a box into fragments creating new borders, padding and repeating backgrounds + * or lets it stay as a continuous box on a page break, column break, or, for inline + * elements, at a line break. + */ + boxDecorationBreak?: ICSSRule | string; + + /** + * Deprecated + */ + boxDirection?: ICSSRule | string; + + /** + * Do not use. This property has been replaced by the flex-wrap property. + * Gets or sets a value that specifies the direction to add successive rows or columns + * when the value of box-lines is set to multiple. + */ + boxLineProgression?: ICSSRule | string; + + /** + * Do not use. This property has been replaced by the flex-wrap property. + * Gets or sets a value that specifies whether child elements wrap onto multiple lines + * or columns based on the space available in the object. + */ + boxLines?: ICSSRule | string; + + /** + * Do not use. This property has been replaced by flex-order. + * Specifies the ordinal group that a child element of the object belongs to. This + * ordinal value identifies the display order (along the axis defined by the box-orient + * property) for the group. + */ + boxOrdinalGroup?: ICSSRule | string; + + /** + * Deprecated. + */ + boxFlex?: ICSSRule | number; + + /** + * Deprecated. + */ + boxFlexGroup?: ICSSRule | number; + + /** + * Cast a drop shadow from the frame of almost any element. + * MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow + */ + boxShadow?: ICSSRule | string; + + /** + * The CSS box-sizing property is used to alter the default CSS box model used to + * calculate width and height of the elements. + */ + boxSizing?: ICSSRule | 'border-box' | 'content-box'; + + /** + * The CSS break-after property allows you to force a break on multi-column layouts. + * More specifically, it allows you to force a break after an element. It allows you + * to determine if a break should occur, and what type of break it should be. The + * break-after CSS property describes how the page, column or region break behaves + * after the generated box. If there is no generated box, the property is ignored. + */ + breakAfter?: ICSSRule | string; + + /** + * Control page/column/region breaks that fall above a block of content + */ + breakBefore?: ICSSRule | string; + + /** + * Control page/column/region breaks that fall within a block of content + */ + breakInside?: ICSSRule | string; + + /** + * The clear CSS property specifies if an element can be positioned next to or must be + * positioned below the floating elements that precede it in the markup. + */ + clear?: ICSSRule | string; + + /** + * Deprecated; see clip-path. + * Lets you specify the dimensions of an absolutely positioned element that should be + * visible, and the element is clipped into this shape, and displayed. + */ + clip?: ICSSRule | string; + + /** + * Clipping crops an graphic, so that only a portion of the graphic is rendered, or + * filled. This clip-rule property, when used with the clip-path property, defines + * which clip rule, or algorithm, to use when filling the different parts of a graphics. + */ + clipRule?: ICSSRule | string; + + /** + * The color property sets the color of an element's foreground content (usually text), + * accepting any standard CSS color from keywords and hex values to RGB(a) and HSL(a). + */ + color?: ICSSRule | string; + + /** + * Describes the number of columns of the element. + * See CSS 3 column-count property https://www.w3.org/TR/css3-multicol/#cc + */ + columnCount?: ICSSRule | number | 'auto'; + + /** + * Specifies how to fill columns (balanced or sequential). + */ + columnFill?: ICSSRule | string; + + /** + * The column-gap property controls the width of the gap between columns in multi-column + * elements. + */ + columnGap?: ICSSRule | string; + + /** + * Sets the width, style, and color of the rule between columns. + */ + columnRule?: ICSSRule | string; + + /** + * Specifies the color of the rule between columns. + */ + columnRuleColor?: ICSSRule | string; + + /** + * Specifies the width of the rule between columns. + */ + columnRuleWidth?: ICSSRule | string; + + /** + * The column-span CSS property makes it possible for an element to span across all + * columns when its value is set to all. An element that spans more than one column + * is called a spanning element. + */ + columnSpan?: ICSSRule | string; + + /** + * Specifies the width of columns in multi-column elements. + */ + columnWidth?: ICSSRule | string; + + /** + * This property is a shorthand property for setting column-width and/or column-count. + */ + columns?: ICSSRule | string; + + /** + * Content for pseudo selectors. + */ + content?: string; + + /** + * The counter-increment property accepts one or more names of counters (identifiers), + * each one optionally followed by an integer which specifies the value by which the + * counter should be incremented (e.g. if the value is 2, the counter increases by 2 + * each time it is invoked). + */ + counterIncrement?: ICSSRule | string; + + /** + * The counter-reset property contains a list of one or more names of counters, each + * one optionally followed by an integer (otherwise, the integer defaults to 0.) Each + * time the given element is invoked, the counters specified by the property are set to the given integer. + */ + counterReset?: ICSSRule | string; + + /** + * The cue property specifies sound files (known as an "auditory icon") to be played by + * speech media agents before and after presenting an element's content; if only one + * file is specified, it is played both before and after. The volume at which the + * file(s) should be played, relative to the volume of the main element, may also be + * specified. The icon files may also be set separately with the cue-before and + * cue-after properties. + */ + cue?: ICSSRule | string; + + /** + * The cue-after property specifies a sound file (known as an "auditory icon") to be + * played by speech media agents after presenting an element's content; the volume at + * which the file should be played may also be specified. The shorthand property cue + * sets cue sounds for both before and after the element is presented. + */ + cueAfter?: ICSSRule | string; + + /** + * Specifies the mouse cursor displayed when the mouse pointer is over an element. + */ + cursor?: ICSSRule | string; + + /** + * The direction CSS property specifies the text direction/writing direction. The rtl + * is used for Hebrew or Arabic text, the ltr is for other languages. + */ + direction?: ICSSRule | string; + + /** + * This property specifies the type of rendering box used for an element. It is a + * shorthand property for many other display properties. + */ + display?: ICSSRule | string; + + /** + * The ‘fill’ property paints the interior of the given graphical element. The area to + * be painted consists of any areas inside the outline of the shape. To determine the + * inside of the shape, all subpaths are considered, and the interior is determined + * according to the rules associated with the current value of the ‘fill-rule’ + * property. The zero-width geometric outline of a shape is included in the area to be + * painted. + */ + fill?: ICSSRule | string; + + /** + * SVG: Specifies the opacity of the color or the content the current object is filled + * with. + * See SVG 1.1 https://www.w3.org/TR/SVG/painting.html#FillOpacityProperty + */ + fillOpacity?: ICSSRule | number; + + /** + * The ‘fill-rule’ property indicates the algorithm which is to be used to determine + * what parts of the canvas are included inside the shape. For a simple, + * non-intersecting path, it is intuitively clear what region lies "inside"; however, + * for a more complex path, such as a path that intersects itself or where one subpath + * encloses another, the interpretation of "inside" is not so obvious. + * The ‘fill-rule’ property provides two options for how the inside of a shape is + * determined: + */ + fillRule?: ICSSRule | string; + + /** + * Applies various image processing effects. This property is largely unsupported. See + * Compatibility section for more information. + */ + filter?: ICSSRule | string; + + /** + * Shorthand for `flex-grow`, `flex-shrink`, and `flex-basis`. + */ + flex?: ICSSRule | number | string; + + /** + * Obsolete, do not use. This property has been renamed to align-items. + * Specifies the alignment (perpendicular to the layout axis defined by the + * flex-direction property) of child elements of the object. + */ + flexAlign?: ICSSRule | string; + + /** + * The flex-basis CSS property describes the initial main size of the flex item before + * any free space is distributed according to the flex factors described in the flex + * property (flex-grow and flex-shrink). + */ + flexBasis?: ICSSRule | string; + + /** + * The flex-direction CSS property describes how flex items are placed in the flex + * container, by setting the direction of the flex container's main axis. + */ + flexDirection?: ICSSRule | 'row' | 'row-reverse' | 'column' | 'column-reverse'; + + /** + * The flex-flow CSS property defines the flex container's main and cross axis. It is + * a shorthand property for the flex-direction and flex-wrap properties. + */ + flexFlow?: ICSSRule | string; + + /** + * Specifies the flex grow factor of a flex item. + * See CSS flex-grow property https://drafts.csswg.org/css-flexbox-1/#flex-grow-property + */ + flexGrow?: ICSSRule | number; + + /** + * Do not use. This property has been renamed to align-self + * Specifies the alignment (perpendicular to the layout axis defined by flex-direction) of child elements of the object. + */ + flexItemAlign?: ICSSRule | string; + + /** + * Do not use. This property has been renamed to align-content. + * Specifies how a flexbox's lines align within the flexbox when there is extra space + * along the axis that is perpendicular to the axis defined by the flex-direction + * property. + */ + flexLinePack?: ICSSRule | string; + + /** + * Gets or sets a value that specifies the ordinal group that a flexbox element + * belongs to. This ordinal value identifies the display order for the group. + */ + flexOrder?: ICSSRule | string; + + /** + * Specifies the flex shrink factor of a flex item. + * See CSS flex-shrink property https://drafts.csswg.org/css-flexbox-1/#flex-shrink-property + */ + flexShrink?: ICSSRule | number; + + /** + * Specifies whether flex items are forced into a single line or can be wrapped onto + * multiple lines. If wrapping is allowed, this property also enables you to control + * the direction in which lines are stacked. + * See CSS flex-wrap property https://drafts.csswg.org/css-flexbox-1/#flex-wrap-property + */ + flexWrap?: ICSSRule | 'nowrap' | 'wrap' | 'wrap-reverse'; + + /** + * Elements which have the style float are floated horizontally. These elements can + * move as far to the left or right of the containing element. All elements after + * the floating element will flow around it, but elements before the floating element + * are not impacted. If several floating elements are placed after each other, they + * will float next to each other as long as there is room. + */ + float?: ICSSRule | string; + + /** + * Flows content from a named flow (specified by a corresponding flow-into) through + * selected elements to form a dynamic chain of layout regions. + */ + flowFrom?: ICSSRule | string; + + /** + * Lays out one or more grid items bound by 4 grid lines. Shorthand for setting + * grid-column-start, grid-column-end, grid-row-start, and grid-row-end in a single + * declaration. + */ + gridArea?: ICSSRule | string; + + /** + * Controls a grid item's placement in a grid area, particularly grid position and a + * grid span. Shorthand for setting grid-column-start and grid-column-end in a single + * declaration. + */ + gridColumn?: ICSSRule | string; + + /** + * Controls a grid item's placement in a grid area as well as grid position and a + * grid span. The grid-column-end property (with grid-row-start, grid-row-end, and + * grid-column-start) determines a grid item's placement by specifying the grid lines + * of a grid item's grid area. + */ + gridColumnEnd?: ICSSRule | string; + + /** + * Determines a grid item's placement by specifying the starting grid lines of a grid + * item's grid area . A grid item's placement in a grid area consists of a grid + * position and a grid span. See also ( grid-row-start, grid-row-end, and + * grid-column-end) + */ + gridColumnStart?: ICSSRule | string; + + /** + * Gets or sets a value that indicates which row an element within a Grid should + * appear in. Shorthand for setting grid-row-start and grid-row-end in a single + * declaration. + */ + gridRow?: ICSSRule | string; + + /** + * Determines a grid item’s placement by specifying the block-end. A grid item's + * placement in a grid area consists of a grid position and a grid span. The + * grid-row-end property (with grid-row-start, grid-column-start, and grid-column-end) + * determines a grid item's placement by specifying the grid lines of a grid item's + * grid area. + */ + gridRowEnd?: ICSSRule | string; + + /** + * Specifies a row position based upon an integer location, string value, or desired + * row size. + * css/properties/grid-row is used as short-hand for grid-row-position and + * grid-row-position + */ + gridRowPosition?: ICSSRule | string; + + gridRowSpan?: ICSSRule | string; + + /** + * Specifies named grid areas which are not associated with any particular grid item, + * but can be referenced from the grid-placement properties. The syntax of the + * grid-template-areas property also provides a visualization of the structure of the + * grid, making the overall layout of the grid container easier to understand. + */ + gridTemplateAreas?: ICSSRule | string; + + /** + * Specifies (with grid-template-rows) the line names and track sizing functions of + * the grid. Each sizing function can be specified as a length, a percentage of the + * grid container’s size, a measurement of the contents occupying the column or row, + * or a fraction of the free space in the grid. + */ + gridTemplateColumns?: ICSSRule | string; + + /** + * Specifies (with grid-template-columns) the line names and track sizing functions of + * the grid. Each sizing function can be specified as a length, a percentage of the + * grid container’s size, a measurement of the contents occupying the column or row, + * or a fraction of the free space in the grid. + */ + gridTemplateRows?: ICSSRule | string; + + /** + * Sets the height of an element. The content area of the element height does not + * include the padding, border, and margin of the element. + */ + height?: ICSSRule | string; + + /** + * Specifies the minimum number of characters in a hyphenated word + */ + hyphenateLimitChars?: ICSSRule | string; + + /** + * Indicates the maximum number of successive hyphenated lines in an element. The + * ‘no-limit’ value means that there is no limit. + */ + hyphenateLimitLines?: ICSSRule | string; + + /** + * Specifies the maximum amount of trailing whitespace (before justification) that may + * be left in a line before hyphenation is triggered to pull part of a word from the + * next line back up into the current one. + */ + hyphenateLimitZone?: ICSSRule | string; + + /** + * Specifies whether or not words in a sentence can be split by the use of a manual or + * automatic hyphenation mechanism. + */ + hyphens?: ICSSRule | string; + + imeMode?: ICSSRule | string; + + /** + * Defines how the browser distributes space between and around flex items + * along the main-axis of their container. + * See CSS justify-content property + * https://www.w3.org/TR/css-flexbox-1/#justify-content-property + */ + justifyContent?: ICSSRule | 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around' | 'space-evenly'; + + layoutGrid?: ICSSRule | string; + + layoutGridChar?: ICSSRule | string; + + layoutGridLine?: ICSSRule | string; + + layoutGridMode?: ICSSRule | string; + + layoutGridType?: ICSSRule | string; + + /** + * Sets the left position of an element relative to the nearest anscestor that is set + * to position absolute, relative, or fixed. + */ + left?: ICSSRule | number | string; + + /** + * The letter-spacing CSS property specifies the spacing behavior between text + * characters. + */ + letterSpacing?: ICSSRule | string; + + /** + * Deprecated. Gets or sets line-breaking rules for text in selected languages such as + * Japanese, Chinese, and Korean. + */ + lineBreak?: ICSSRule | string; + + lineClamp?: ICSSRule | number; + + /** + * Specifies the height of an inline block level element. + * See CSS 2.1 line-height property https://www.w3.org/TR/CSS21/visudet.html#propdef-line-height + */ + lineHeight?: ICSSRule | 'normal' | number | ICSSLengthRule | ICSSPercentageRule; + + /** + * Shorthand property that sets the list-style-type, list-style-position and + * list-style-image properties in one declaration. + */ + listStyle?: ICSSRule | string; + + /** + * This property sets the image that will be used as the list item marker. When the + * image is available, it will replace the marker set with the 'list-style-type' + * marker. That also means that if the image is not available, it will show the style + * specified by list-style-property + */ + listStyleImage?: ICSSRule | string; + + /** + * Specifies if the list-item markers should appear inside or outside the content flow. + */ + listStylePosition?: ICSSRule | string; + + /** + * Specifies the type of list-item marker in a list. + */ + listStyleType?: ICSSRule | string; + + /** + * The margin property is shorthand to allow you to set all four margins of an element + * at once. Its equivalent longhand properties are margin-top, margin-right, + * margin-bottom and margin-left. Negative values are also allowed. + */ + margin?: ICSSRule | number | string; + + /** + * margin-bottom sets the bottom margin of an element. + */ + marginBottom?: ICSSRule | number | string; + + /** + * margin-left sets the left margin of an element. + */ + marginLeft?: ICSSRule | number | string; + + /** + * margin-right sets the right margin of an element. + */ + marginRight?: ICSSRule | number | string; + + /** + * margin-top sets the top margin of an element. + */ + marginTop?: ICSSRule | number | string; + + /** + * The marquee-direction determines the initial direction in which the marquee content moves. + */ + marqueeDirection?: ICSSRule | string; + + /** + * The 'marquee-style' property determines a marquee's scrolling behavior. + */ + marqueeStyle?: ICSSRule | string; + + /** + * This property is shorthand for setting mask-image, mask-mode, mask-repeat, + * mask-position, mask-clip, mask-origin, mask-composite and mask-size. Omitted + * values are set to their original properties' initial values. + */ + mask?: ICSSRule | string; + + /** + * This property is shorthand for setting mask-border-source, mask-border-slice, + * mask-border-width, mask-border-outset, and mask-border-repeat. Omitted values + * are set to their original properties' initial values. + */ + maskBorder?: ICSSRule | string; + + /** + * This property specifies how the images for the sides and the middle part of the + * mask image are scaled and tiled. The first keyword applies to the horizontal + * sides, the second one applies to the vertical ones. If the second keyword is + * absent, it is assumed to be the same as the first, similar to the CSS + * border-image-repeat property. + */ + maskBorderRepeat?: ICSSRule | string; + + /** + * This property specifies inward offsets from the top, right, bottom, and left + * edges of the mask image, dividing it into nine regions: four corners, four + * edges, and a middle. The middle image part is discarded and treated as fully + * transparent black unless the fill keyword is present. The four values set the + * top, right, bottom and left offsets in that order, similar to the CSS + * border-image-slice property. + */ + maskBorderSlice?: ICSSRule | string; + + /** + * Specifies an image to be used as a mask. An image that is empty, fails to + * download, is non-existent, or cannot be displayed is ignored and does not mask + * the element. + */ + maskBorderSource?: ICSSRule | string; + + /** + * This property sets the width of the mask box image, similar to the CSS + * border-image-width property. + */ + maskBorderWidth?: ICSSRule | string; + + /** + * Determines the mask painting area, which defines the area that is affected by + * the mask. The painted content of an element may be restricted to this area. + */ + maskClip?: ICSSRule | string; + + /** + * For elements rendered as a single box, specifies the mask positioning area. For + * elements rendered as multiple boxes (e.g., inline boxes on several lines, boxes + * on several pages) specifies which boxes box-decoration-break operates on to + * determine the mask positioning area(s). + */ + maskOrigin?: ICSSRule | string; + + /** + * This property must not be used. It is no longer included in any standard or + * standard track specification, nor is it implemented in any browser. It is only + * used when the text-align-last property is set to size. It controls allowed + * adjustments of font-size to fit line content. + */ + maxFontSize?: ICSSRule | string; + + /** + * Sets the maximum height for an element. It prevents the height of the element to + * exceed the specified value. If min-height is specified and is greater than + * max-height, max-height is overridden. + */ + maxHeight?: ICSSRule | string; + + /** + * Sets the maximum width for an element. It limits the width property to be larger + * than the value specified in max-width. + */ + maxWidth?: ICSSRule | string; + + /** + * Sets the minimum height for an element. It prevents the height of the element to + * be smaller than the specified value. The value of min-height overrides both + * max-height and height. + */ + minHeight?: ICSSRule | string; + + /** + * Sets the minimum width of an element. It limits the width property to be not + * smaller than the value specified in min-width. + */ + minWidth?: ICSSRule | string; + + /** + * Specifies the transparency of an element. + * See CSS 3 opacity property https://drafts.csswg.org/css-color-3/#opacity + */ + opacity?: ICSSRule | number; + + /** + * Specifies the order used to lay out flex items in their flex container. + * Elements are laid out in the ascending order of the order value. + * See CSS order property https://drafts.csswg.org/css-flexbox-1/#order-property + */ + order?: ICSSRule | number; + + /** + * In paged media, this property defines the minimum number of lines in + * a block container that must be left at the bottom of the page. + * See CSS 3 orphans, widows properties https://drafts.csswg.org/css-break-3/#widows-orphans + */ + orphans?: ICSSRule | number; + + /** + * The CSS outline property is a shorthand property for setting one or more of the + * individual outline properties outline-style, outline-width and outline-color in a + * single rule. In most cases the use of this shortcut is preferable and more + * convenient. + * Outlines differ from borders in the following ways: + * • Outlines do not take up space, they are drawn above the content. + * • Outlines may be non-rectangular. They are rectangular in + * Gecko/Firefox. Internet Explorer attempts to place the smallest contiguous outline + * around all elements or shapes that are indicated to have an outline. Opera draws a + * non-rectangular shape around a construct. + */ + outline?: ICSSRule | 0 | string; + + /** + * The outline-color property sets the color of the outline of an element. An + * outline is a line that is drawn around elements, outside the border edge, to make + * the element stand out. + */ + outlineColor?: ICSSRule | string; + + /** + * The outline-offset property offsets the outline and draw it beyond the border edge. + */ + outlineOffset?: ICSSRule | string; + + /** + * The overflow property controls how extra content exceeding the bounding box of an + * element is rendered. It can be used in conjunction with an element that has a + * fixed width and height, to eliminate text-induced page distortion. + */ + overflow?: ICSSRule | 'auto' | 'hidden' | 'scroll' | 'visible'; + + /** + * Specifies the preferred scrolling methods for elements that overflow. + */ + overflowStyle?: ICSSRule | string; + + /** + * Specifies whether or not the browser should insert line breaks within words to + * prevent text from overflowing its content box. In contrast to word-break, + * overflow-wrap will only create a break if an entire word cannot be placed on its + * own line without overflowing. + */ + overflowWrap?: ICSSRule | 'normal' | 'break-word'; + + /** + * Controls how extra content exceeding the x-axis of the bounding box of an element + * is rendered. + */ + overflowX?: ICSSRule | 'auto' | 'hidden' | 'scroll' | 'visible'; + + /** + * Controls how extra content exceeding the y-axis of the bounding box of an element + * is rendered. + */ + overflowY?: ICSSRule | 'auto' | 'hidden' | 'scroll' | 'visible'; + + /** + * The padding optional CSS property sets the required padding space on one to four + * sides of an element. The padding area is the space between an element and its + * border. Negative values are not allowed but decimal values are permitted. The + * element size is treated as fixed, and the content of the element shifts toward the + * center as padding is increased. The padding property is a shorthand to avoid + * setting each side separately (padding-top, padding-right, padding-bottom, + * padding-left). + */ + padding?: ICSSRule | number | string; + + /** + * The padding-bottom CSS property of an element sets the padding space required on + * the bottom of an element. The padding area is the space between the content of the + * element and its border. Contrary to margin-bottom values, negative values of + * padding-bottom are invalid. + */ + paddingBottom?: ICSSRule | number | string; + + /** + * The padding-left CSS property of an element sets the padding space required on the + * left side of an element. The padding area is the space between the content of the + * element and its border. Contrary to margin-left values, negative values of + * padding-left are invalid. + */ + paddingLeft?: ICSSRule | number | string; + + /** + * The padding-right CSS property of an element sets the padding space required on the + * right side of an element. The padding area is the space between the content of the + * element and its border. Contrary to margin-right values, negative values of + * padding-right are invalid. + */ + paddingRight?: ICSSRule | number | string; + + /** + * The padding-top CSS property of an element sets the padding space required on the + * top of an element. The padding area is the space between the content of the element + * and its border. Contrary to margin-top values, negative values of padding-top are + * invalid. + */ + paddingTop?: ICSSRule | number | string; + + /** + * The page-break-after property is supported in all major browsers. With CSS3, + * page-break-* properties are only aliases of the break-* properties. The CSS3 + * Fragmentation spec defines breaks for all CSS box fragmentation. + */ + pageBreakAfter?: ICSSRule | string; + + /** + * The page-break-before property sets the page-breaking behavior before an element. + * With CSS3, page-break-* properties are only aliases of the break-* properties. The + * CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. + */ + pageBreakBefore?: ICSSRule | string; + + /** + * Sets the page-breaking behavior inside an element. With CSS3, page-break-* + * properties are only aliases of the break-* properties. The CSS3 Fragmentation spec + * defines breaks for all CSS box fragmentation. + */ + pageBreakInside?: ICSSRule | string; + + /** + * The pause property determines how long a speech media agent should pause before and + * after presenting an element. It is a shorthand for the pause-before and pause-after + * properties. + */ + pause?: ICSSRule | string; + + /** + * The pause-after property determines how long a speech media agent should pause after + * presenting an element. It may be replaced by the shorthand property pause, which + * sets pause time before and after. + */ + pauseAfter?: ICSSRule | string; + + /** + * The pause-before property determines how long a speech media agent should pause + * before presenting an element. It may be replaced by the shorthand property pause, + * which sets pause time before and after. + */ + pauseBefore?: ICSSRule | string; + + /** + * The perspective property defines how far an element is placed from the view on the + * z-axis, from the screen to the viewer. Perspective defines how an object is viewed. + * In graphic arts, perspective is the representation on a flat surface of what the + * viewer's eye would see in a 3D space. (See Wikipedia for more information about + * graphical perspective and for related illustrations.) + * The illusion of perspective on a flat surface, such as a computer screen, is created + * by projecting points on the flat surface as they would appear if the flat surface + * were a window through which the viewer was looking at the object. In discussion of + * virtual environments, this flat surface is called a projection plane. + */ + perspective?: ICSSRule | string; + + /** + * The perspective-origin property establishes the origin for the perspective property. + * It effectively sets the X and Y position at which the viewer appears to be looking + * at the children of the element. + * When used with perspective, perspective-origin changes the appearance of an object, + * as if a viewer were looking at it from a different origin. An object appears + * differently if a viewer is looking directly at it versus looking at it from below, + * above, or from the side. Thus, the perspective-origin is like a vanishing point. + * The default value of perspective-origin is 50% 50%. This displays an object as if + * the viewer's eye were positioned directly at the center of the screen, both + * top-to-bottom and left-to-right. A value of 0% 0% changes the object as if the + * viewer was looking toward the top left angle. A value of 100% 100% changes the + * appearance as if viewed toward the bottom right angle. + */ + perspectiveOrigin?: ICSSRule | string; + + /** + * The pointer-events property allows you to control whether an element can be the + * target for the pointing device (e.g, mouse, pen) events. + */ + pointerEvents?: ICSSRule | string; + + /** + * The position property controls the type of positioning used by an element within + * its parent elements. The effect of the position property depends on a lot of + * factors, for example the position property of parent elements. + */ + position?: ICSSRule | 'static' | 'relative' | 'absolute' | 'fixed' | 'sticky'; + + /** + * Obsolete: unsupported. + * This property determines whether or not a full-width punctuation mark character + * should be trimmed if it appears at the beginning of a line, so that its "ink" lines + * up with the first glyph in the line above and below. + */ + punctuationTrim?: ICSSRule | string; + + /** + * Sets the type of quotation marks for embedded quotations. + */ + quotes?: ICSSRule | string; + + /** + * Controls whether the last region in a chain displays additional 'overset' content + * according its default overflow property, or if it displays a fragment of content + * as if it were flowing into a subsequent region. + */ + regionFragment?: ICSSRule | string; + + /** + * The rest-after property determines how long a speech media agent should pause after + * presenting an element's main content, before presenting that element's exit cue + * sound. It may be replaced by the shorthand property rest, which sets rest time + * before and after. + */ + restAfter?: ICSSRule | string; + + /** + * The rest-before property determines how long a speech media agent should pause after + * presenting an intro cue sound for an element, before presenting that element's main + * content. It may be replaced by the shorthand property rest, which sets rest time + * before and after. + */ + restBefore?: ICSSRule | string; + + /** + * Specifies the position an element in relation to the right side of the containing + * element. + */ + right?: ICSSRule | number | string; + + rubyAlign?: ICSSRule | string; + + rubyPosition?: ICSSRule | string; + + /** + * Defines the alpha channel threshold used to extract a shape from an image. Can be + * thought of as a "minimum opacity" threshold; that is, a value of 0.5 means that the + * shape will enclose all the pixels that are more than 50% opaque. + */ + shapeImageThreshold?: ICSSRule | string; + + /** + * A future level of CSS Shapes will define a shape-inside property, which will define + * a shape to wrap content within the element. See Editor's Draft + * and CSSWG wiki page on next-level plans + * + */ + shapeInside?: ICSSRule | string; + + /** + * Adds a margin to a shape-outside. In effect, defines a new shape that is the + * smallest contour around all the points that are the shape-margin distance outward + * perpendicular to each point on the underlying shape. For points where a + * perpendicular direction is not defined (e.g., a triangle corner), takes all + * points on a circle centered at the point and with a radius of the shape-margin + * distance. This property accepts only non-negative values. + */ + shapeMargin?: ICSSRule | string; + + /** + * Declares a shape around which text should be wrapped, with possible modifications + * from the shape-margin property. The shape defined by shape-outside and shape-margin + * changes the geometry of a float element's float area. + */ + shapeOutside?: ICSSRule | string; + + /** + * The speak property determines whether or not a speech synthesizer will read aloud + * the contents of an element. + */ + speak?: ICSSRule | string; + + /** + * The speak-as property determines how the speech synthesizer interprets the content: + * words as whole words or as a sequence of letters, numbers as a numerical value or a + * sequence of digits, punctuation as pauses in speech or named punctuation characters. + */ + speakAs?: ICSSRule | string; + + /** + * SVG: Specifies the opacity of the outline on the current object. + * See SVG 1.1 https://www.w3.org/TR/SVG/painting.html#StrokeOpacityProperty + */ + strokeOpacity?: ICSSRule | number; + + /** + * SVG: Specifies the width of the outline on the current object. + * See SVG 1.1 https://www.w3.org/TR/SVG/painting.html#StrokeWidthProperty + */ + strokeWidth?: ICSSRule | ICSSPercentageRule | ICSSLengthRule; + + /** + * The tab-size CSS property is used to customise the width of a tab (U+0009) character. + */ + tabSize?: ICSSRule | string; + + /** + * The 'table-layout' property controls the algorithm used to lay out the table cells, rows, and columns. + */ + tableLayout?: ICSSRule | string; + + /** + * The text-align CSS property describes how inline content like text is aligned in its + * parent block element. text-align does not control the alignment of block elements + * itself, only their inline content. + */ + textAlign?: ICSSRule | string; + + /** + * The text-align-last CSS property describes how the last line of a block element or + * a line before line break is aligned in its parent block element. + */ + textAlignLast?: ICSSRule | string; + + /** + * The text-decoration CSS property is used to set the text formatting to underline, + * overline, line-through or blink. underline and overline decorations are positioned + * under the text, line-through over it. + */ + textDecoration?: ICSSRule | string; + + /** + * Sets the color of any text decoration, such as underlines, overlines, and strike + * throughs. + */ + textDecorationColor?: ICSSRule | string; + + /** + * Sets what kind of line decorations are added to an element, such as underlines, + * overlines, etc. + */ + textDecorationLine?: ICSSRule | string; + + textDecorationLineThrough?: ICSSRule | string; + + textDecorationNone?: ICSSRule | string; + + textDecorationOverline?: ICSSRule | string; + + /** + * Specifies what parts of an element’s content are skipped over when applying any + * text decoration. + */ + textDecorationSkip?: ICSSRule | string; + + /** + * This property specifies the style of the text decoration line drawn on the + * specified element. The intended meaning for the values are the same as those of + * the border-style-properties. + */ + textDecorationStyle?: ICSSRule | string; + + textDecorationUnderline?: ICSSRule | string; + + /** + * The text-emphasis property will apply special emphasis marks to the elements text. + * Slightly similar to the text-decoration property only that this property can have + * affect on the line-height. It also is noted that this is shorthand for + * text-emphasis-style and for text-emphasis-color. + */ + textEmphasis?: ICSSRule | string; + + /** + * The text-emphasis-color property specifies the foreground color of the emphasis + * marks. + */ + textEmphasisColor?: ICSSRule | string; + + /** + * The text-emphasis-style property applies special emphasis marks to an element's + * text. + */ + textEmphasisStyle?: ICSSRule | string; + + /** + * This property helps determine an inline box's block-progression dimension, derived + * from the text-height and font-size properties for non-replaced elements, the height + * or the width for replaced elements, and the stacked block-progression dimension for + * inline-block elements. The block-progression dimension determines the position of + * the padding, border and margin for the element. + */ + textHeight?: ICSSRule | string; + + /** + * Specifies the amount of space horizontally that should be left on the first line of + * the text of an element. This horizontal spacing is at the beginning of the first + * line and is in respect to the left edge of the containing block box. + */ + textIndent?: ICSSRule | string; + + textJustifyTrim?: ICSSRule | string; + + textKashidaSpace?: ICSSRule | string; + + /** + * The text-line-through property is a shorthand property for text-line-through-style, + * text-line-through-color and text-line-through-mode. (Considered obsolete; use + * text-decoration instead.) + */ + textLineThrough?: ICSSRule | string; + + /** + * Specifies the line colors for the line-through text decoration. + * (Considered obsolete; use text-decoration-color instead.) + */ + textLineThroughColor?: ICSSRule | string; + + /** + * Sets the mode for the line-through text decoration, determining whether the text + * decoration affects the space characters or not. (Considered obsolete; use + * text-decoration-skip instead.) + */ + textLineThroughMode?: ICSSRule | string; + + /** + * Specifies the line style for line-through text decoration. + * (Considered obsolete; use text-decoration-style instead.) + */ + textLineThroughStyle?: ICSSRule | string; + + /** + * Specifies the line width for the line-through text decoration. + */ + textLineThroughWidth?: ICSSRule | string; + + /** + * The text-overflow shorthand CSS property determines how overflowed content that is + * not displayed is signaled to the users. It can be clipped, display an ellipsis + * ('…', U+2026 HORIZONTAL ELLIPSIS) or a Web author-defined string. It covers the + * two long-hand properties text-overflow-mode and text-overflow-ellipsis + */ + textOverflow?: ICSSRule | string; + + /** + * The text-overline property is the shorthand for the text-overline-style, + * text-overline-width, text-overline-color, and text-overline-mode properties. + */ + textOverline?: ICSSRule | string; + + /** + * Specifies the line color for the overline text decoration. + */ + textOverlineColor?: ICSSRule | string; + + /** + * Sets the mode for the overline text decoration, determining whether the text + * decoration affects the space characters or not. + */ + textOverlineMode?: ICSSRule | string; + + /** + * Specifies the line style for overline text decoration. + */ + textOverlineStyle?: ICSSRule | string; + + /** + * Specifies the line width for the overline text decoration. + */ + textOverlineWidth?: ICSSRule | string; + + /** + * The text-rendering CSS property provides information to the browser about how to + * optimize when rendering text. Options are: legibility, speed or geometric precision. + */ + textRendering?: ICSSRule | string; + + /** + * Obsolete: unsupported. + */ + textScript?: ICSSRule | string; + + /** + * The CSS text-shadow property applies one or more drop shadows to the text and + * of an element. Each shadow is specified as an offset from the + * text, along with optional color and blur radius values. + */ + textShadow?: ICSSRule | string; + + /** + * This property transforms text for styling purposes. (It has no effect on the + * underlying content.) + */ + textTransform?: ICSSRule | string; + + /** + * Unsupported. + * This property will add a underline position value to the element that has an + * underline defined. + */ + textUnderlinePosition?: ICSSRule | string; + + /** + * After review this should be replaced by text-decoration should it not? + * This property will set the underline style for text with a line value for + * underline, overline, and line-through. + */ + textUnderlineStyle?: ICSSRule | string; + + /** + * This property specifies how far an absolutely positioned box's top margin edge is + * offset below the top edge of the box's containing block. For relatively positioned + * boxes, the offset is with respect to the top edges of the box itself (i.e., the box + * is given a position in the normal flow, then offset from that position according to + * these properties). + */ + top?: ICSSRule | number | string; + + /** + * Determines whether touch input may trigger default behavior supplied by the user + * agent, such as panning or zooming. + */ + touchAction?: ICSSRule | string; + + /** + * CSS transforms allow elements styled with CSS to be transformed in two-dimensional + * or three-dimensional space. Using this property, elements can be translated, + * rotated, scaled, and skewed. The value list may consist of 2D and/or 3D transform + * values. + */ + transform?: ICSSRule | string; + + /** + * This property defines the origin of the transformation axes relative to the element + * to which the transformation is applied. + */ + transformOrigin?: ICSSRule | string; + + /** + * This property allows you to define the relative position of the origin of the + * transformation grid along the z-axis. + */ + transformOriginZ?: ICSSRule | string; + + /** + * This property specifies how nested elements are rendered in 3D space relative to their parent. + */ + transformStyle?: ICSSRule | string; + + /** + * The transition CSS property is a shorthand property for transition-property, + * transition-duration, transition-timing-function, and transition-delay. It allows to + * define the transition between two states of an element. + */ + transition?: ICSSRule | string; + + /** + * Defines when the transition will start. A value of ‘0s’ means the transition will + * execute as soon as the property is changed. Otherwise, the value specifies an + * offset from the moment the property is changed, and the transition will delay + * execution by that offset. + */ + transitionDelay?: ICSSRule | string; + + /** + * The 'transition-duration' property specifies the length of time a transition + * animation takes to complete. + */ + transitionDuration?: ICSSRule | string; + + /** + * The 'transition-property' property specifies the name of the CSS property to which + * the transition is applied. + */ + transitionProperty?: ICSSRule | string; + + /** + * Sets the pace of action within a transition + */ + transitionTimingFunction?: ICSSRule | string; + + /** + * The unicode-bidi CSS property specifies the level of embedding with respect to the bidirectional algorithm. + */ + unicodeBidi?: ICSSRule | string; + + /** + * This is for all the high level UX stuff. + */ + userFocus?: ICSSRule | string; + + /** + * For inputing user content + */ + userInput?: ICSSRule | string; + + /** + * Defines the text selection behavior. + */ + userSelect?: ICSSRule | 'none' | 'auto' | 'text' | 'all' | 'contain'; + + /** + * The vertical-align property controls how inline elements or text are vertically + * aligned compared to the baseline. If this property is used on table-cells it + * controls the vertical alignment of content of the table cell. + */ + verticalAlign?: ICSSRule | string; + + /** + * The visibility property specifies whether the boxes generated by an element are rendered. + */ + visibility?: ICSSRule | string; + + /** + * The voice-balance property sets the apparent position (in stereo sound) of the synthesized voice for spoken media. + */ + voiceBalance?: ICSSRule | string; + + /** + * The voice-duration property allows the author to explicitly set the amount of time + * it should take a speech synthesizer to read an element's content, for example to + * allow the speech to be synchronized with other media. With a value of auto (the + * default) the length of time it takes to read the content is determined by the + * content itself and the voice-rate property. + */ + voiceDuration?: ICSSRule | string; + + /** + * The voice-family property sets the speaker's voice used by a speech media agent to + * read an element. The speaker may be specified as a named character (to match a + * voice option in the speech reading software) or as a generic description of the + * age and gender of the voice. Similar to the font-family property for visual media, + * a comma-separated list of fallback options may be given in case the speech reader + * does not recognize the character name or cannot synthesize the requested combination + * of generic properties. + */ + voiceFamily?: ICSSRule | string; + + /** + * The voice-pitch property sets pitch or tone (high or low) for the synthesized speech + * when reading an element; the pitch may be specified absolutely or relative to the + * normal pitch for the voice-family used to read the text. + */ + voicePitch?: ICSSRule | string; + + /** + * The voice-range property determines how much variation in pitch or tone will be + * created by the speech synthesize when reading an element. Emphasized text, + * grammatical structures and punctuation may all be rendered as changes in pitch, + * this property determines how strong or obvious those changes are; large ranges are + * associated with enthusiastic or emotional speech, while small ranges are associated + * with flat or mechanical speech. + */ + voiceRange?: ICSSRule | string; + + /** + * The voice-rate property sets the speed at which the voice synthesized by a speech + * media agent will read content. + */ + voiceRate?: ICSSRule | string; + + /** + * The voice-stress property sets the level of vocal emphasis to be used for + * synthesized speech reading the element. + */ + voiceStress?: ICSSRule | string; + + /** + * The voice-volume property sets the volume for spoken content in speech media. It + * replaces the deprecated volume property. + */ + voiceVolume?: ICSSRule | string; + + /** + * The white-space property controls whether and how white space inside the element is + * collapsed, and whether lines may wrap at unforced "soft wrap" opportunities. + */ + whiteSpace?: ICSSRule | string; + + /** + * Obsolete: unsupported. + */ + whiteSpaceTreatment?: ICSSRule | string; + + /** + * In paged media, this property defines the mimimum number of lines that must be left + * at the top of the second page. + * See CSS 3 orphans, widows properties + * https://drafts.csswg.org/css-break-3/#widows-orphans + */ + widows?: ICSSRule | number; + + /** + * Specifies the width of the content area of an element. The content area of the element + * width does not include the padding, border, and margin of the element. + */ + width?: ICSSRule | string; + + /** + * The word-break property is often used when there is long generated content that is + * strung together without and spaces or hyphens to beak apart. A common case of this + * is when there is a long URL that does not have any hyphens. This case could + * potentially cause the breaking of the layout as it could extend past the parent + * element. + */ + wordBreak?: ICSSRule | string; + + /** + * The word-spacing CSS property specifies the spacing behavior between "words". + */ + wordSpacing?: ICSSRule | string; + + /** + * An alias of css/properties/overflow-wrap, word-wrap defines whether to break + * words when the content exceeds the boundaries of its container. + */ + wordWrap?: ICSSRule | string; + + /** + * Specifies how exclusions affect inline content within block-level elements. Elements + * lay out their inline content in their content area but wrap around exclusion areas. + */ + wrapFlow?: ICSSRule | string; + + /** + * Set the value that is used to offset the inner wrap shape from other shapes. Inline + * content that intersects a shape with this property will be pushed by this shape's + * margin. + */ + wrapMargin?: ICSSRule | string; + + /** + * Obsolete and unsupported. Do not use. + * This CSS property controls the text when it reaches the end of the block in which it is enclosed. + */ + wrapOption?: ICSSRule | string; + + /** + * writing-mode specifies if lines of text are laid out horizontally or vertically, + * and the direction which lines of text and blocks progress. + */ + writingMode?: ICSSRule | string; + + /** + * The z-index property specifies the z-order of an element and its descendants. + * When elements overlap, z-order determines which one covers the other. + * See CSS 2 z-index property https://www.w3.org/TR/CSS2/visuren.html#z-index + */ + zIndex?: ICSSRule | 'auto' | number; + + /** + * Sets the initial zoom factor of a document defined by @viewport. + * See CSS zoom descriptor https://drafts.csswg.org/css-device-adapt/#zoom-desc + */ + zoom?: ICSSRule | 'auto' | number | ICSSPercentageRule; +} diff --git a/packages/merge-styles/src/IStyle.ts b/packages/merge-styles/src/IStyle.ts new file mode 100644 index 00000000000000..8550c60befad6f --- /dev/null +++ b/packages/merge-styles/src/IStyle.ts @@ -0,0 +1,22 @@ +import { IRawStyle } from './IRawStyle'; + +/** + * IStyleObject extends a raw style objects, but allows selectors to be defined + * under the selectors node. + * @public + */ +export interface IExtendedRawStyle extends IRawStyle { + displayName?: string; + selectors?: { + [key: string]: IStyle; + }; +} + +export type IStyleBase = IExtendedRawStyle | string | boolean | null | undefined; + +/** + * IStyleObject extends a raw style objects, but allows selectors to be defined + * under the selectors node. + * @public + */ +export type IStyle = IStyleBase | IStyleBase[] | IStyleBase[][] | IStyleBase[][][]; diff --git a/packages/merge-styles/src/IStyleSet.ts b/packages/merge-styles/src/IStyleSet.ts new file mode 100644 index 00000000000000..82926ab5b49a81 --- /dev/null +++ b/packages/merge-styles/src/IStyleSet.ts @@ -0,0 +1,5 @@ +import { IStyle } from './IStyle'; + +export type IStyleSet = { + [key: string]: IStyle; +}; diff --git a/packages/merge-styles/src/Stylesheet.ts b/packages/merge-styles/src/Stylesheet.ts new file mode 100644 index 00000000000000..be0bb3a5a60a4f --- /dev/null +++ b/packages/merge-styles/src/Stylesheet.ts @@ -0,0 +1,161 @@ +import { GlobalSettings } from '@uifabric/utilities/lib/GlobalSettings'; +import { FabricPerformance } from '@uifabric/utilities/lib/FabricPerformance'; +import { IStyle } from './IStyle'; +const STYLESHEET_SETTING = 'stylesheet'; + +export const enum InjectionMode { + none = 0, + insertNode = 1, + appendChild = 2 +} + +export interface IStyleSheetConfig { + async?: boolean; + injectionMode?: InjectionMode; +} + +/** + * + * @public + */ +export class Stylesheet { + private _styleElement: HTMLStyleElement; + private _rules: string[]; + private _config: IStyleSheetConfig; + private _rulesToInsert: string[]; + private _timerId: number; + private _counter: number; + private _keyToClassName: { [key: string]: string }; + + // tslint:disable-next-line:no-any + private _classNameToArgs: { [key: string]: any }; + + public static getInstance(): Stylesheet { + return GlobalSettings.getValue(STYLESHEET_SETTING, () => new Stylesheet()); + } + + constructor(config?: IStyleSheetConfig) { + this._config = { + async: false, + injectionMode: InjectionMode.insertNode, + ...config + }; + + this.reset(); + } + + public setConfig(config?: IStyleSheetConfig): void { + this._config = { + ...this._config, + ...config + }; + } + + public getClassName(displayName?: string): string { + let prefix = displayName || 'css'; + + return `${prefix}-${this._counter++}`; + } + + public classNameFromKey(key: string): string | undefined { + return this._keyToClassName[key]; + } + + public cacheClassName(className: string, key: string, args: IStyle[]): void { + this._keyToClassName[key] = className; + this._classNameToArgs[className] = args; + } + + public argsFromClassName(className: string): IStyle[] | undefined { + return this._classNameToArgs[className]; + } + + public insertRule( + rule: string, + forceSync: boolean = false + ): void { + if (this._config.async && !forceSync) { + this._rulesToInsert.push(rule); + if (!this._timerId) { + this._timerId = setTimeout(() => { + this._timerId = 0; + this._insertRule(this._rulesToInsert); + this._rulesToInsert = []; + }, 0); + } + } else { + this._insertRule(rule); + } + } + + public getRules(): string { + return (this._rules.join('') || '') + (this._rulesToInsert.join('') || ''); + } + + public reset(): void { + this._rules = []; + this._rulesToInsert = []; + this._counter = 0; + this._classNameToArgs = {}; + this._keyToClassName = {}; + + if (this._timerId) { + clearTimeout(this._timerId); + this._timerId = 0; + } + } + + private _insertRule(rule: string | string[]): void { + let element = this._getElement(); + let injectionMode = element ? this._config.injectionMode : InjectionMode.none; + + switch (injectionMode) { + + case InjectionMode.appendChild: + FabricPerformance.measure('appendChild', () => { + element.appendChild(document.createTextNode( + (Array.isArray(rule)) ? rule.join('') : rule + )); + }); + break; + + case InjectionMode.insertNode: + let { sheet } = element; + if (Array.isArray(rule)) { + for (let i = 0; i < rule.length; i++) { + this._insertRule(rule[i]); + } + } else { + FabricPerformance.measure('insertRule', () => { + try { + // tslint:disable-next-line:no-any + (sheet as any).insertRule(rule, (sheet as any).cssRules.length); + } catch (e) { + console.log( + `insertRule failed.\n${e}\nRule: ${rule}` + ); + } + + }); + } + break; + + default: + if (Array.isArray(rule)) { + this._rules = this._rules.concat(rule); + } else { + this._rules.push(rule); + } + break; + } + } + + private _getElement(): HTMLStyleElement { + if (!this._styleElement) { + this._styleElement = document.createElement('style'); + document.head.appendChild(this._styleElement); + } + + return this._styleElement; + } +} diff --git a/packages/merge-styles/src/common/tests.js b/packages/merge-styles/src/common/tests.js new file mode 100644 index 00000000000000..ec92b700322036 --- /dev/null +++ b/packages/merge-styles/src/common/tests.js @@ -0,0 +1,22 @@ +'use strict'; + + +/** + * This is a test entry point to help karma-webpack find all tests in the project. + **/ + +// Polyfills +require('es6-weak-map/implement'); +require('es6-map/implement'); +console.log('hi') +// Before loading modules, treat errors and warnings as test failures. +console.error = console.warn = function (warning) { + throw new Error(warning); +} + +var context = require.context('..', true, /.+\.test\.js?$/); + +context.keys().forEach(context); + + +module.exports = context; diff --git a/packages/merge-styles/src/concatStyleSets.test.ts b/packages/merge-styles/src/concatStyleSets.test.ts new file mode 100644 index 00000000000000..bd4f46fa5120ed --- /dev/null +++ b/packages/merge-styles/src/concatStyleSets.test.ts @@ -0,0 +1,43 @@ +import { concatStyleSets } from './concatStyleSets'; + +let { expect } = chai; + +describe('concatStyleSets', () => { + it('can concat style sets', () => { + + // tslint:disable-next-line:no-any + let result = concatStyleSets( + { + root: { background: 'red' }, + a: { background: 'green' } + }, + { + a: { background: 'white' }, + b: { background: 'blue' } + }, + { + root: { + selectors: { + ':hover': { background: 'yellow' } + } + } + } + ); + + expect(result).eqls({ + root: [ + { background: 'red' }, + { + selectors: { + ':hover': { background: 'yellow' } + } + } + ], + a: [ + { background: 'green' }, + { background: 'white' } + ], + b: { background: 'blue' } + }); + }); +}); \ No newline at end of file diff --git a/packages/merge-styles/src/concatStyleSets.ts b/packages/merge-styles/src/concatStyleSets.ts new file mode 100644 index 00000000000000..78a43232d66e4d --- /dev/null +++ b/packages/merge-styles/src/concatStyleSets.ts @@ -0,0 +1,33 @@ +import { IStyleSet } from './IStyleSet'; + +/** + * Combine a set of styles together (but does not register css classes.) + * @public + */ +export function concatStyleSets(...args: (T | false | null | undefined)[]): T { + let mergedSet: IStyleSet = {}; + + for (let i = 0; i < args.length; i++) { + let currentSet = args[i]; + + if (currentSet) { + for (let prop in currentSet) { + if (currentSet.hasOwnProperty(prop)) { + let mergedValue = mergedSet[prop]; + let currentValue = currentSet[prop]; + + if (mergedValue === undefined) { + mergedSet[prop] = currentValue; + } else { + mergedSet[prop] = [ + ...(Array.isArray(mergedValue) ? mergedValue : [mergedValue]), + ...(Array.isArray(currentValue) ? currentValue : [currentValue]) + ]; + } + } + } + } + } + + return mergedSet as T; +} \ No newline at end of file diff --git a/packages/merge-styles/src/fontFace.test.ts b/packages/merge-styles/src/fontFace.test.ts new file mode 100644 index 00000000000000..ac5cbf2997b55a --- /dev/null +++ b/packages/merge-styles/src/fontFace.test.ts @@ -0,0 +1,20 @@ +import { fontFace } from './fontFace'; +import { + Stylesheet, + InjectionMode +} from './Stylesheet'; + +let { expect } = chai; +let _stylesheet: Stylesheet = Stylesheet.getInstance(); + +_stylesheet.setConfig({ injectionMode: InjectionMode.none }); + +describe('fontFace', () => { + it('can register a font face', () => { + fontFace({ + fontFamily: 'Segoe UI', + src: 'url("foo")' + }); + expect(_stylesheet.getRules()).equals('@font-face{font-family:Segoe UI;src:url("foo");}'); + }); +}); \ No newline at end of file diff --git a/packages/merge-styles/src/fontFace.ts b/packages/merge-styles/src/fontFace.ts new file mode 100644 index 00000000000000..67785016c2b395 --- /dev/null +++ b/packages/merge-styles/src/fontFace.ts @@ -0,0 +1,11 @@ +import { Stylesheet } from './Stylesheet'; +import { IFontFace } from './IRawStyle'; +import { serializeRuleEntries } from './styleToClassName'; + +/** + * Registers a font face. + * @public + */ +export function fontFace(font: IFontFace): void { + Stylesheet.getInstance().insertRule(`@font-face{${serializeRuleEntries(font as {})}}`); +} diff --git a/packages/merge-styles/src/getVendorSettings.ts b/packages/merge-styles/src/getVendorSettings.ts new file mode 100644 index 00000000000000..fdc77502458ab7 --- /dev/null +++ b/packages/merge-styles/src/getVendorSettings.ts @@ -0,0 +1,41 @@ +export interface IVendorSettings { + isWebkit?: boolean; + isMoz?: boolean; + isMs?: boolean; + isOpera?: boolean; +} + +let _vendorSettings: IVendorSettings | undefined; + +export function getVendorSettings(): IVendorSettings { + if (!_vendorSettings) { + let doc = typeof document !== 'undefined' ? document : undefined; + let nav = typeof navigator !== 'undefined' ? navigator : undefined; + let userAgent = nav ? nav.userAgent.toLowerCase() : undefined; + + if (!doc) { + _vendorSettings = { + isWebkit: true, + isMoz: true, + isOpera: true, + isMs: true + }; + } else { + _vendorSettings = { + isWebkit: !!(doc && 'WebkitAppearance' in doc.documentElement.style), + isMoz: !!(userAgent && userAgent.indexOf('firefox') > -1), + isOpera: !!(userAgent && userAgent.indexOf('opera') > -1), + isMs: !!(nav && (/rv:11.0/i.test(nav.userAgent) || /Edge\/\d./i.test(navigator.userAgent))) + }; + } + } + + return _vendorSettings; +} + +/** + * Sets the vendor settings for prefixing and vendor specific operations. + */ +export function setVendorSettings(vendorSettings?: IVendorSettings): void { + _vendorSettings = vendorSettings; +} \ No newline at end of file diff --git a/packages/merge-styles/src/index.ts b/packages/merge-styles/src/index.ts new file mode 100644 index 00000000000000..62fb2a0c467c01 --- /dev/null +++ b/packages/merge-styles/src/index.ts @@ -0,0 +1,34 @@ +export { + IExtendedRawStyle, + IStyle +} from './IStyle'; + +export { + IRawStyle, + IFontFace, + IFontWeight +} from './IRawStyle'; + +export { + mergeStyles +} from './mergeStyles'; + +export { + mergeStyleSets +} from './mergeStyleSets'; + +export { + concatStyleSets +} from './concatStyleSets'; + +export { + fontFace +} from './fontFace'; + +export { + keyframes +} from './keyframes'; + +export { + Stylesheet +} from './Stylesheet'; diff --git a/packages/merge-styles/src/keyframes.ts b/packages/merge-styles/src/keyframes.ts new file mode 100644 index 00000000000000..6141f8bca8c7e0 --- /dev/null +++ b/packages/merge-styles/src/keyframes.ts @@ -0,0 +1,41 @@ +import { getVendorSettings } from './getVendorSettings'; +import { Stylesheet } from './Stylesheet'; +import { serializeRuleEntries } from './styleToClassName'; + +/** + * + * @public + */ +export function keyframes(timeline: { [key: string]: {} }): string { + let vendorSettings = getVendorSettings(); + let stylesheet = Stylesheet.getInstance(); + let name = stylesheet.getClassName(); + + let rulesArray: string[] = []; + + for (let prop in timeline) { + if (timeline.hasOwnProperty(prop)) { + rulesArray.push(prop, ' {', serializeRuleEntries(timeline[prop]), '}'); + } + } + let rules = rulesArray.join(''); + + stylesheet.insertRule(`@keyframes ${name}{${rules}}`); + + if (vendorSettings.isWebkit) { + stylesheet.insertRule(`@-webkit-keyframes ${name}{${rules}}`); + } + if (vendorSettings.isMoz) { + stylesheet.insertRule(`@-moz-keyframes ${name}{${rules}}`); + } + + if (vendorSettings.isOpera) { + stylesheet.insertRule(`@-o-keyframes ${name}{${rules}}`); + } + + if (vendorSettings.isMs) { + stylesheet.insertRule(`@-ms-keyframes ${name}{${rules}}`); + } + + return name; +} diff --git a/packages/merge-styles/src/mergeStyleSets.ts b/packages/merge-styles/src/mergeStyleSets.ts new file mode 100644 index 00000000000000..c9929aaf011a5a --- /dev/null +++ b/packages/merge-styles/src/mergeStyleSets.ts @@ -0,0 +1,27 @@ +import { mergeStyles } from './mergeStyles'; +import { concatStyleSets } from './concatStyleSets'; +import { IStyle } from './IStyle'; + +/** + * Allows you to pass in 1 or more sets of areas which will return a merged + * set of classes. + * + * @public + */ +export function mergeStyleSets( + ...cssSets: T[] +): {[P in keyof T]?: string } { + let classNameSet: {[P in keyof T]?: string } = {}; + let cssSet = cssSets[0]; + + if (cssSets.length > 1) { + cssSet = concatStyleSets(...cssSets); + } + for (let prop in cssSet) { + if (cssSet.hasOwnProperty(prop)) { + classNameSet[prop] = mergeStyles(cssSet[prop] as IStyle); + } + } + + return classNameSet; +} diff --git a/packages/merge-styles/src/mergeStyles.test.ts b/packages/merge-styles/src/mergeStyles.test.ts new file mode 100644 index 00000000000000..d1377df05d2439 --- /dev/null +++ b/packages/merge-styles/src/mergeStyles.test.ts @@ -0,0 +1,29 @@ +import { mergeStyles } from './mergeStyles'; +import { + Stylesheet, + InjectionMode +} from './Stylesheet'; + +let { expect } = chai; +let _stylesheet: Stylesheet = Stylesheet.getInstance(); + +_stylesheet.setConfig({ injectionMode: InjectionMode.none }); + +describe('mergeStyles', () => { + beforeEach(() => { + _stylesheet.reset(); + }); + + it('can join strings', () => { + expect(mergeStyles('a', false, null, undefined, 'b')).equals('a b'); + }); + + it('can join arrays of strings', () => { + expect(mergeStyles(['a', 'b', 'c'], false, null, undefined)).equals('a b c'); + }); + + it('can mix styles and classnames together', () => { + expect(mergeStyles('foo', { background: 'red' })).equals('foo css-0'); + expect(_stylesheet.getRules()).equals('.css-0{background:red;}'); + }); +}); diff --git a/packages/merge-styles/src/mergeStyles.ts b/packages/merge-styles/src/mergeStyles.ts new file mode 100644 index 00000000000000..23420b248a342d --- /dev/null +++ b/packages/merge-styles/src/mergeStyles.ts @@ -0,0 +1,36 @@ +import { IStyle } from './IStyle'; +import { styleToClassName } from './styleToClassName'; + +/** + * Concatination helper, which can merge class names together. Skips over falsey values. + * + * @public + */ +export function mergeStyles(...args: (IStyle | IStyle[])[]): string { + let classes: string[] = []; + let objects: {}[] = []; + + function _processArgs(argsList: (IStyle | IStyle[])[]): void { + for (let i = 0; i < argsList.length; i++) { + let arg = argsList[i]; + + if (arg) { + if (typeof arg === 'string') { + classes.push(arg); + } else if (Array.isArray(arg)) { + _processArgs(arg); + } else if (typeof arg === 'object') { + objects.push(arg); + } + } + } + } + + _processArgs(args); + + if (objects.length) { + classes.push(styleToClassName(objects)); + } + + return classes.join(' '); +} diff --git a/packages/merge-styles/src/server.ts b/packages/merge-styles/src/server.ts new file mode 100644 index 00000000000000..26882cb6715b19 --- /dev/null +++ b/packages/merge-styles/src/server.ts @@ -0,0 +1,17 @@ +import { InjectionMode, Stylesheet } from './Stylesheet'; + +export function renderStatic( + onRender: () => string +): { html: string, css: string } { + let stylesheet = Stylesheet.getInstance(); + + stylesheet.setConfig({ + injectionMode: InjectionMode.none + }); + stylesheet.reset(); + + return { + html: onRender(), + css: stylesheet.getRules() + }; +} \ No newline at end of file diff --git a/packages/merge-styles/src/styleToClassName.test.ts b/packages/merge-styles/src/styleToClassName.test.ts new file mode 100644 index 00000000000000..d3332c3f69b6fe --- /dev/null +++ b/packages/merge-styles/src/styleToClassName.test.ts @@ -0,0 +1,114 @@ +import 'es6-map/implement'; +import { setRTL } from '@uifabric/utilities/lib/rtl'; +import { styleToClassName } from './styleToClassName'; +import { + InjectionMode, + Stylesheet +} from './Stylesheet'; + +let { expect } = chai; +let _stylesheet: Stylesheet = Stylesheet.getInstance(); + +_stylesheet.setConfig({ injectionMode: InjectionMode.none }); + +describe('styleToClassName', () => { + beforeEach(() => { + _stylesheet.reset(); + }); + + it('can register classes and avoid re-registering', () => { + let className = styleToClassName({ background: 'red' }); + + expect(className).equals('css-0'); + expect(_stylesheet.getRules()).equals('.css-0{background:red;}'); + + className = styleToClassName({ background: 'red' }); + + expect(className).equals('css-0'); + expect(_stylesheet.getRules()).equals('.css-0{background:red;}'); + + className = styleToClassName({ background: 'green' }); + + expect(className).equals('css-1'); + expect(_stylesheet.getRules()).equals('.css-0{background:red;}.css-1{background:green;}'); + }); + + it('can register pseudo selectors', () => { + let className = styleToClassName({ + selectors: { + ':hover': { background: 'red' } + } + }); + + expect(className).equals('css-0'); + expect(_stylesheet.getRules()).equals('.css-0:hover{background:red;}'); + }); + + it('can register parent and sibling selectors', () => { + let className = styleToClassName({ + selectors: { + '& .child': { background: 'red' }, + '.parent &': { background: 'green' } + } + }); + + expect(className).equals('css-0'); + expect(_stylesheet.getRules()).equals('.css-0 .child{background:red;}.parent .css-0{background:green;}'); + }); + + it('can merge rules', () => { + let className = styleToClassName( + null, + false, + undefined, + { backgroundColor: 'red', color: 'white' }, + { backgroundColor: 'green' } + ); + + expect(className).equals('css-0'); + expect(_stylesheet.getRules()).equals('.css-0{background-color:green;color:white;}'); + + className = styleToClassName({ backgroundColor: 'green', color: 'white' }); + expect(className).equals('css-0'); + }); + + it('returns blank string with no input', () => { + expect(styleToClassName()).equals(''); + }); + + it('can preserve displayName in names', () => { + expect(styleToClassName({ displayName: 'DisplayName', background: 'red' })).equals('DisplayName-0'); + expect(_stylesheet.getRules()).equals('.DisplayName-0{background:red;}'); + }); + + it('can flip rtl and add units', () => { + setRTL(true); + + styleToClassName({ left: 40 }); + expect(_stylesheet.getRules()).equals('.css-0{right:40px;}'); + + setRTL(false); + }); + + it('can prefix webkit specific things', () => { + styleToClassName({ WebkitFontSmoothing: 'none' }); + expect(_stylesheet.getRules()).equals('.css-0{-webkit-font-smoothing:none;}'); + }); + + it('can expand previously defined rules', () => { + let className = styleToClassName({ background: 'red' }); + let newClassName = styleToClassName(className, { color: 'white' }); + + expect(newClassName).equals('css-1'); + expect(_stylesheet.getRules()).equals('.css-0{background:red;}.css-1{background:red;color:white;}'); + }); + + it('can expand an array of rules', () => { + styleToClassName([ + { background: 'red' }, + { background: 'white' } + ]); + expect(_stylesheet.getRules()).equals('.css-0{background:white;}'); + }); + +}); diff --git a/packages/merge-styles/src/styleToClassName.ts b/packages/merge-styles/src/styleToClassName.ts new file mode 100644 index 00000000000000..026bf184be3869 --- /dev/null +++ b/packages/merge-styles/src/styleToClassName.ts @@ -0,0 +1,179 @@ +import { GlobalSettings } from '@uifabric/utilities/lib/GlobalSettings'; +import { rtlifyRules } from './transforms/rtlifyRules'; +import { provideUnits } from './transforms/provideUnits'; +import { prefixRules } from './transforms/prefixRules'; +import { expandQuads } from './transforms/expandQuads'; +import { getVendorSettings } from './getVendorSettings'; +import { Stylesheet } from './Stylesheet'; +import { IStyle } from './IStyle'; + +const DISPLAY_NAME = 'displayName'; + +function toRuleEntry(name: string, value: string): string | undefined { + if (name === DISPLAY_NAME) { + return undefined; + } + + // Prefixes like WebKit need a dash infront of them. + if (/[A-Z]/.test(name[0])) { + name = '-' + name; + } + + // Kebab case the rule. + let rules: string[] = [ + name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(), + value + ]; + + let ruleEntries: string[] = []; + + // Apply transforms. + provideUnits(rules); + rtlifyRules(rules); + prefixRules(rules); + expandQuads(rules); + + // Stringify the rules. + for (let i = 0; i < rules.length; i += 2) { + ruleEntries.push(rules[i], ':', rules[i + 1], ';'); + } + + return ruleEntries.join(''); +} + +function getDisplayName(rules?: Map): string | undefined { + let rootStyle: IStyle = rules && rules.get('&'); + + // tslint:disable-next-line:no-any + return rootStyle && (rootStyle as any).displayName; +} + +/** + * Given an array of objects or strings, iterate through each: + * if string, look up Map. Merge map into current map. + * else if object: + * iterate through each prop: + * if is a selector. + * + * + * edge cases; should :active always have prescidence over :hover? + * ([':hover': {}, ':active': {}], [':hover': {}]) + */ +function extractRules( + args: IStyle[], + rules: Map = new Map(), + currentSelector: string = '&' +): Map { + let stylesheet = Stylesheet.getInstance(); + let currentRules: {} | undefined = rules.get(currentSelector); + + if (!currentRules) { + currentRules = {}; + rules.set(currentSelector, currentRules); + } + + for (let i = 0; i < args.length; i++) { + const arg: IStyle = args[i]; + + // If the arg is a string, we need to look up the class map and merge. + if (typeof arg === 'string') { + let expandedRules = stylesheet.argsFromClassName(arg); + + if (expandedRules) { + extractRules(expandedRules, rules); + } + // Else if the arg is an array, we need to recurse in. + } else if (Array.isArray(arg)) { + extractRules(arg, rules, currentSelector); + } else { + // tslint:disable-next-line:no-any + for (let prop in (arg as any)) { + if (prop === 'selectors') { + // tslint:disable-next-line:no-any + let selectors: { [key: string]: IStyle } = (arg as any).selectors; + + for (let newSelector in selectors) { + if (selectors.hasOwnProperty(newSelector)) { + let selectorValue = selectors[newSelector]; + + if (newSelector.indexOf('&') < 0) { + newSelector = currentSelector + newSelector; + } + extractRules([selectorValue], rules, newSelector); + } + } + } else { + // Else, add the rule to the currentSelector. + // tslint:disable-next-line:no-any + (currentRules as any)[prop] = (arg as any)[prop] as any; + } + } + } + } + + return rules; +} + +function serializeRules(rules: Map): string | undefined { + let serialized: string[] = []; + let hasProps = false; + + rules.forEach((ruleEntries: { [key: string]: string }, selector: string): void => { + serialized.push(selector); + + for (let propName in ruleEntries) { + if (ruleEntries.hasOwnProperty(propName)) { + hasProps = true; + serialized.push(propName); + serialized.push(ruleEntries[propName]); + } + } + }); + + return hasProps ? serialized.join('') : undefined; +} + +export function serializeRuleEntries(ruleEntries: { [key: string]: string }): string { + let allEntries: string[] = []; + + if (ruleEntries) { + for (let entry in ruleEntries) { + if (ruleEntries.hasOwnProperty(entry)) { + allEntries.push(toRuleEntry(entry, ruleEntries[entry])!); + } + } + } + + return allEntries.join(''); +} + +export function styleToClassName(...args: IStyle[]): string { + let rules: Map = extractRules(args); + let key = serializeRules(rules); + let className = ''; + + if (key) { + let stylesheet = Stylesheet.getInstance(); + + className = stylesheet.classNameFromKey(key)!; + + if (!className) { + className = stylesheet.getClassName(getDisplayName(rules)); + stylesheet.cacheClassName(className, key, args); + + let ruleSelectors = rules.keys(); + let selector = ruleSelectors.next().value; + + while (selector) { + let rulesToInsert: string = serializeRuleEntries(rules.get(selector) as {}); + + if (rulesToInsert) { + selector = selector.replace('&', `.${className}`); + stylesheet.insertRule(`${selector}{${rulesToInsert}}`); + } + selector = ruleSelectors.next().value; + } + } + } + return className; +} diff --git a/packages/merge-styles/src/transforms/expandQuads.test.ts b/packages/merge-styles/src/transforms/expandQuads.test.ts new file mode 100644 index 00000000000000..65a4f7acacd9ed --- /dev/null +++ b/packages/merge-styles/src/transforms/expandQuads.test.ts @@ -0,0 +1,37 @@ +import { expandQuads } from './expandQuads'; + +import { expect } from 'chai'; + +describe('expandQuads', () => { + it('can expand margins and paddings', () => { + let rules = ['margin', '0px 1px 2px 3px']; + + expandQuads(rules); + + expect(rules).eqls([ + 'marginTop', + '0px', + 'marginRight', + '1px', + 'marginBottom', + '2px', + 'marginLeft', + '3px' + ]); + + rules = ['padding', '0px 1px 2px 3px']; + + expandQuads(rules); + + expect(rules).eqls([ + 'paddingTop', + '0px', + 'paddingRight', + '1px', + 'paddingBottom', + '2px', + 'paddingLeft', + '3px' + ]); + }); +}); diff --git a/packages/merge-styles/src/transforms/expandQuads.ts b/packages/merge-styles/src/transforms/expandQuads.ts new file mode 100644 index 00000000000000..1788c6eaf6d2ca --- /dev/null +++ b/packages/merge-styles/src/transforms/expandQuads.ts @@ -0,0 +1,31 @@ +import { IVendorSettings } from '../getVendorSettings'; + +export function expandQuads( + rulePairs: string[], + vendorSettings?: IVendorSettings +): void { + for (let nameIndex = 0; nameIndex < rulePairs.length; nameIndex += 2) { + let name = rulePairs[nameIndex]; + + switch (name) { + case 'margin': + case 'padding': + let parts = rulePairs[nameIndex + 1].split(' '); + + rulePairs.splice( + nameIndex, + 2, + name + 'Top', + parts[0], + name + 'Right', + parts[1] || parts[0], + name + 'Bottom', + parts[2] || parts[0], + name + 'Left', + parts[3] || parts[1] || parts[0], + ); + + nameIndex += 6; + } + } +} diff --git a/packages/merge-styles/src/transforms/prefixRules.test.ts b/packages/merge-styles/src/transforms/prefixRules.test.ts new file mode 100644 index 00000000000000..577aa093798b11 --- /dev/null +++ b/packages/merge-styles/src/transforms/prefixRules.test.ts @@ -0,0 +1,67 @@ +import { prefixRules } from './prefixRules'; +import { setVendorSettings } from '../getVendorSettings'; +import { expect } from 'chai'; + +const AUTO_TRANSLATED_RULES = [ + 'user-select' +]; + +describe('prefixRules', () => { + after(() => { + setVendorSettings(undefined); + }); + + it('can provide translate webkit rules', () => { + AUTO_TRANSLATED_RULES.forEach((rule: string) => { + let rules = [rule, 'none']; + + setVendorSettings({ isWebkit: true }); + prefixRules(rules); + + expect(rules).eql([ + rule, 'none', + '-webkit-' + rule, 'none' + ]); + }); + }); + + it('can provide translate moz rules', () => { + AUTO_TRANSLATED_RULES.forEach((rule: string) => { + let rules = [rule, 'none']; + + setVendorSettings({ isMoz: true }); + prefixRules(rules); + expect(rules).eql([ + rule, 'none', + '-moz-' + rule, 'none' + ]); + }); + }); + + it('can provide translate ms rules', () => { + AUTO_TRANSLATED_RULES.forEach((rule: string) => { + let rules = [rule, 'none']; + + setVendorSettings({ isMs: true }); + prefixRules(rules); + expect(rules).eql([ + rule, 'none', + '-ms-' + rule, 'none' + ]); + }); + }); + + it('can provide translate opera rules', () => { + AUTO_TRANSLATED_RULES.forEach((rule: string) => { + let rules = [rule, 'none']; + + setVendorSettings({ isOpera: true }); + prefixRules(rules); + expect(rules).eql([ + rule, 'none', + '-o-' + rule, 'none' + ]); + }); + }); + +}); \ No newline at end of file diff --git a/packages/merge-styles/src/transforms/prefixRules.ts b/packages/merge-styles/src/transforms/prefixRules.ts new file mode 100644 index 00000000000000..4069080998444b --- /dev/null +++ b/packages/merge-styles/src/transforms/prefixRules.ts @@ -0,0 +1,31 @@ +import { getVendorSettings } from '../getVendorSettings'; + +let autoPrefixNames: { [key: string]: number } = { + 'user-select': 1 +}; + +export function prefixRules( + rulePairs: string[] +): void { + let vendorSettings = getVendorSettings(); + + for (let nameIndex = 0, valueIndex = 1; nameIndex < rulePairs.length; nameIndex += 2, valueIndex += 2) { + let name = rulePairs[nameIndex]; + let value = rulePairs[valueIndex]; + + if (autoPrefixNames[name]) { + if (vendorSettings.isWebkit) { + rulePairs.push('-webkit-' + name, value); + } + if (vendorSettings.isMoz) { + rulePairs.push('-moz-' + name, value); + } + if (vendorSettings.isMs) { + rulePairs.push('-ms-' + name, value); + } + if (vendorSettings.isOpera) { + rulePairs.push('-o-' + name, value); + } + } + } +} \ No newline at end of file diff --git a/packages/merge-styles/src/transforms/provideUnits.test.ts b/packages/merge-styles/src/transforms/provideUnits.test.ts new file mode 100644 index 00000000000000..e356d7a90b8bfd --- /dev/null +++ b/packages/merge-styles/src/transforms/provideUnits.test.ts @@ -0,0 +1,48 @@ +import { provideUnits } from './provideUnits'; + +import { expect } from 'chai'; + +describe('provideUnits', () => { + it('can provide units', () => { + let propertiesToTest = [ + 'left', + 'right', + 'top', + 'bottom', + 'borderWidth' + ].forEach((property: string) => { + let testSet: (string | number)[] = [property, 1]; + + provideUnits(testSet); + + expect(testSet).eql([property, '1px']); + }); + }); + + it('can provide units for directional props', () => { + let propertiesToTest = [ + 'padding', + 'margin', + 'border' + ].forEach((property: string) => { + let testSet: (string | number)[] = [ + property, 1, + property + 'Left', 1, + property + 'Right', 1, + property + 'Top', 1, + property + 'Bottom', 1 + ]; + + provideUnits(testSet); + + expect(testSet).eql([ + property, '1px', + property + 'Left', '1px', + property + 'Right', '1px', + property + 'Top', '1px', + property + 'Bottom', '1px' + ]); + }); + + }); +}); \ No newline at end of file diff --git a/packages/merge-styles/src/transforms/provideUnits.ts b/packages/merge-styles/src/transforms/provideUnits.ts new file mode 100644 index 00000000000000..9374ca550e5bb0 --- /dev/null +++ b/packages/merge-styles/src/transforms/provideUnits.ts @@ -0,0 +1,31 @@ +let PX_BASED_PROPERTIES: string[] = [ + 'borderRadius', + 'borderWidth', + 'bottom', + 'left', + 'right', + 'top', +]; + +[ + 'border', + 'margin', + 'padding' +].forEach((prop: string) => { + PX_BASED_PROPERTIES.push( + prop, + prop + 'Left', + prop + 'Right', + prop + 'Top', + prop + 'Bottom' + ); +}); + +export function provideUnits(rulePairs: (string | number)[]): void { + for (let i = 0; i < rulePairs.length; i += 2) { + let value = rulePairs[i + 1]; + if (typeof value === 'number' && PX_BASED_PROPERTIES.indexOf(rulePairs[i] as string) >= 0) { + rulePairs[i + 1] = `${value}px`; + } + } +} diff --git a/packages/merge-styles/src/transforms/rtlifyRules.test.ts b/packages/merge-styles/src/transforms/rtlifyRules.test.ts new file mode 100644 index 00000000000000..b524f17a9cb87f --- /dev/null +++ b/packages/merge-styles/src/transforms/rtlifyRules.test.ts @@ -0,0 +1,50 @@ +import { setRTL } from '@uifabric/utilities/lib/rtl'; +import { rtlifyRules } from './rtlifyRules'; + +let { expect } = chai; + +describe('rtlifyRules', () => { + + before(() => { + setRTL(true); + }); + + after(() => { + setRTL(false); + }); + + it('can auto flip or avoid autoflipping with noflip', () => { + [ + [['left', '42'], ['right', '42']], + [['right', '42'], ['left', '42']], + [['float', 'left'], ['float', 'right']], + [['float', 'right'], ['float', 'left']], + [['clear', 'left'], ['clear', 'right']], + [['margin', '42'], ['margin', '42']], + [['margin', '1 2'], ['margin', '1 2']], + [['margin', '1 2 3'], ['margin', '1 2 3']], + [['margin', '1 2 3 4'], ['margin', '1 4 3 2']], + [['marginLeft', '42'], ['marginRight', '42']], + [['marginRight', '42'], ['marginLeft', '42']], + [['padding', '42'], ['padding', '42']], + [['padding', '1 2'], ['padding', '1 2']], + [['padding', '1 2 3'], ['padding', '1 2 3']], + [['padding', '1 2 3 4'], ['padding', '1 4 3 2']], + [['paddingLeft', '42'], ['paddingRight', '42']], + [['paddingRight', '42'], ['paddingLeft', '42']], + [['cursor', 'w-resize'], ['cursor', 'e-resize']], + [['cursor', 'sw-resize'], ['cursor', 'se-resize']], + [['cursor', 'nw-resize'], ['cursor', 'ne-resize']], + [['left', '42px /*noflip*/'], ['left', '42px /*noflip*/']], + [['boxShadow', '42px 0 red'], ['boxShadow', '-42px 0 red']], + [['boxShadow', '-42px 0 red'], ['boxShadow', '42px 0 red']] + ].forEach((test: string[][]) => expect(rtlifyRules(test[0])).eqls(test[1])); + }); + + it('does not flip an unflippable cursor', () => { + let rules = ['cursor', 'hand']; + + expect(rtlifyRules(rules)).eqls(['cursor', 'hand']); + }); + +}); diff --git a/packages/merge-styles/src/transforms/rtlifyRules.ts b/packages/merge-styles/src/transforms/rtlifyRules.ts new file mode 100644 index 00000000000000..9d445bfb52da1f --- /dev/null +++ b/packages/merge-styles/src/transforms/rtlifyRules.ts @@ -0,0 +1,72 @@ +import { getRTL } from '@uifabric/utilities/lib/rtl'; + +const _nameReplacements: { [key: string]: string } = { + 'left': 'right', + 'right': 'left' +}; + +const _valueReplacements: { [key: string]: string } = { + 'w-resize': 'e-resize', + 'sw-resize': 'se-resize', + 'nw-resize': 'ne-resize' +}; + +const NO_FLIP = 'noflip'; + +export function rtlifyRules(rulePairs: string[]): string[] { + if (getRTL()) { + for (let nameIndex = 0, valueIndex = 1; nameIndex < rulePairs.length; nameIndex += 2, valueIndex += 2) { + let name = rulePairs[nameIndex]; + let value = rulePairs[valueIndex]; + + if (value.indexOf(NO_FLIP) >= 0) { + continue; + } else if (name.indexOf('Left') >= 0) { + rulePairs[nameIndex] = name.replace('Left', 'Right'); + } else if (name.indexOf('Right') >= 0) { + rulePairs[nameIndex] = name.replace('Right', 'Left'); + } else if (String(value).indexOf('left') >= 0) { + rulePairs[valueIndex] = value.replace('left', 'right'); + } else if (String(value).indexOf('right') >= 0) { + rulePairs[valueIndex] = value.replace('right', 'left'); + } else if (_nameReplacements[name]) { + rulePairs[nameIndex] = _nameReplacements[name]; + } else if (_valueReplacements[value]) { + rulePairs[valueIndex] = _valueReplacements[value]; + } else { + switch (name) { + case 'margin': + case 'padding': + rulePairs[valueIndex] = flipQuad(value); + break; + case 'boxShadow': + rulePairs[valueIndex] = negateNum(value, 0); + break; + } + } + } + } + + return rulePairs; +} + +function negateNum(value: string, partIndex: number): string { + let parts = value.split(' '); + let numberVal = parseInt(parts[partIndex], 10); + + parts[0] = parts[0].replace(String(numberVal), String(numberVal * -1)); + + return parts.join(' '); +} + +function flipQuad(value: string): string { + if (typeof value === 'string') { + let parts = value.split(' '); + + if (parts.length === 4) { + return `${parts[0]} ${parts[3]} ${parts[2]} ${parts[1]}`; + } + } + + return value; +} \ No newline at end of file diff --git a/packages/merge-styles/tsconfig.json b/packages/merge-styles/tsconfig.json new file mode 100644 index 00000000000000..fb6d04adec19ba --- /dev/null +++ b/packages/merge-styles/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "target": "es5", + "module": "commonjs", + "lib": [ + "es2017", + "dom" + ], + "jsx": "react", + "declaration": true, + "sourceMap": true, + "experimentalDecorators": true, + "importHelpers": true, + "noImplicitAny": true, + "strictNullChecks": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node", + "types": [ + "chai", + "mocha" + ] + }, + "exclude": [ + "api", + "temp", + "node_modules", + "dist", + "lib", + "lib-amd" + ] +} \ No newline at end of file diff --git a/packages/merge-styles/tslint.json b/packages/merge-styles/tslint.json new file mode 100644 index 00000000000000..621ee6ba046052 --- /dev/null +++ b/packages/merge-styles/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": [ + "office-ui-fabric-react-tslint" + ], + "rules": {} +} \ No newline at end of file diff --git a/packages/office-ui-fabric-react/package.json b/packages/office-ui-fabric-react/package.json index 6455245e13806d..a9e594cc58bed9 100644 --- a/packages/office-ui-fabric-react/package.json +++ b/packages/office-ui-fabric-react/package.json @@ -44,7 +44,7 @@ "gutil": "1.6.4", "highlight.js": "^9.6.0", "load-themed-styles-loader": "^0.0.3", - "mocha": "^3.2.0", + "mocha": "^3.3.0", "mocha-loader": "^1.1.1", "node-sass": "^4.5.0", "office-ui-fabric-core": ">=7.1.2 <8.0.0", @@ -58,7 +58,7 @@ "resemblejs": "~2.2.3", "sass-loader": "^6.0.3", "sinon": "^2.3.2", - "source-map-loader": "0.2.1", + "source-map-loader": "^0.2.1", "style-loader": "^0.17.0", "ts-loader": "^2.0.1", "typescript": "2.4.2", diff --git a/packages/utilities/api/utilities.api.ts b/packages/utilities/api/utilities.api.ts index 148a933912c034..64d6c0baddfde2 100644 --- a/packages/utilities/api/utilities.api.ts +++ b/packages/utilities/api/utilities.api.ts @@ -183,7 +183,7 @@ class GlobalSettings { // (undocumented) public static addChangeListener(cb: IChangeEventCallback): void; // (undocumented) - public static getValue < T >(key: string): T; + public static getValue < T >(key: string, defaultValue?: T | (() => T)): T; // (undocumented) public static removeChangeListener(cb: IChangeEventCallback): void; // (undocumented) diff --git a/packages/utilities/package.json b/packages/utilities/package.json index 20ede9718c479a..67e0c849db82b0 100644 --- a/packages/utilities/package.json +++ b/packages/utilities/package.json @@ -32,7 +32,7 @@ "es6-promise": "^4.1.0", "es6-weak-map": "^2.0.2", "gulp": "~3.9.1", - "mocha": "~3.3.0", + "mocha": "^3.3.0", "office-ui-fabric-react-tslint": ">=1.0.0 <2.0.0", "react": "^15.4.2", "react-addons-test-utils": "^15.4.2", diff --git a/packages/utilities/src/GlobalSettings.ts b/packages/utilities/src/GlobalSettings.ts index 199e2e052d87e1..e04f798ef995ec 100644 --- a/packages/utilities/src/GlobalSettings.ts +++ b/packages/utilities/src/GlobalSettings.ts @@ -52,7 +52,11 @@ export interface IChangeEventCallback { * @public */ export class GlobalSettings { - public static getValue(key: string): T { + public static getValue(key: string, defaultValue?: T | (() => T)): T { + if (_globalSettings[key] === undefined) { + _globalSettings[key] = typeof defaultValue === 'function' ? defaultValue() : defaultValue; + } + return _globalSettings[key]; } diff --git a/rush.json b/rush.json index 5443f5216968f9..d28eb68b4c6b6e 100644 --- a/rush.json +++ b/rush.json @@ -15,6 +15,11 @@ "projectFolder": "packages/experiments", "shouldPublish": true }, + { + "packageName": "@uifabric/merge-styles", + "projectFolder": "packages/merge-styles", + "shouldPublish": false + }, { "packageName": "@uifabric/utilities", "projectFolder": "packages/utilities", From dbb03eafdd7847cb1e6ba55a20a5e686146fb6ea Mon Sep 17 00:00:00 2001 From: David Zearing Date: Wed, 16 Aug 2017 13:49:57 -0700 Subject: [PATCH 02/17] Updates to add webpack and slightly reduce the bundle size of merge-styles to 3.4k total. --- common/config/rush/npm-shrinkwrap.json | 566 +----------------------- packages/merge-styles/gulpfile.js | 3 - packages/merge-styles/package.json | 3 +- packages/merge-styles/webpack.config.js | 57 +++ packages/utilities/src/rtl.ts | 5 +- 5 files changed, 80 insertions(+), 554 deletions(-) create mode 100644 packages/merge-styles/webpack.config.js diff --git a/common/config/rush/npm-shrinkwrap.json b/common/config/rush/npm-shrinkwrap.json index 43d2823987586e..aba93b92f2ea62 100644 --- a/common/config/rush/npm-shrinkwrap.json +++ b/common/config/rush/npm-shrinkwrap.json @@ -440,6 +440,11 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.1.1.tgz", "integrity": "sha512-vOk6uEMctu0vQrvuSqFdJyqj1Q0S5VTDL79qtjo+DhRr+1mmaD+tluFSCZqhvi/JUhXSzoZN2BhtstaPEeE8cw==" }, + "async": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", + "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=" + }, "css-loader": { "version": "0.24.0", "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-0.24.0.tgz", @@ -577,6 +582,16 @@ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.10.3.tgz", "integrity": "sha1-zlpuzTEB/tXsCYJ9rCKpwpv7BTU=" }, + "source-map": { + "version": "0.1.43", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.1.43.tgz", + "integrity": "sha1-wkvBRspRfBRx9drL4lcbK3+eM0Y=" + }, + "source-map-loader": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/source-map-loader/-/source-map-loader-0.1.6.tgz", + "integrity": "sha1-wJkD2m1zueU7ftjuUkVZcFHpjpE=" + }, "statuses": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz", @@ -5477,549 +5492,6 @@ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, - "fsevents": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.1.2.tgz", - "integrity": "sha512-Sn44E5wQW4bTHXvQmvSHwqbuiXtduD6Rrjm2ZtUEGbyrig+nUH3t/QD4M4/ZXViY556TBpRgZkHLDx3JxPwxiw==", - "optional": true, - "dependencies": { - "abbrev": { - "version": "1.1.0", - "bundled": true, - "optional": true - }, - "ajv": { - "version": "4.11.8", - "bundled": true, - "optional": true - }, - "ansi-regex": { - "version": "2.1.1", - "bundled": true - }, - "aproba": { - "version": "1.1.1", - "bundled": true, - "optional": true - }, - "are-we-there-yet": { - "version": "1.1.4", - "bundled": true, - "optional": true - }, - "asn1": { - "version": "0.2.3", - "bundled": true, - "optional": true - }, - "assert-plus": { - "version": "0.2.0", - "bundled": true, - "optional": true - }, - "asynckit": { - "version": "0.4.0", - "bundled": true, - "optional": true - }, - "aws-sign2": { - "version": "0.6.0", - "bundled": true, - "optional": true - }, - "aws4": { - "version": "1.6.0", - "bundled": true, - "optional": true - }, - "balanced-match": { - "version": "0.4.2", - "bundled": true - }, - "bcrypt-pbkdf": { - "version": "1.0.1", - "bundled": true, - "optional": true - }, - "block-stream": { - "version": "0.0.9", - "bundled": true - }, - "boom": { - "version": "2.10.1", - "bundled": true - }, - "brace-expansion": { - "version": "1.1.7", - "bundled": true - }, - "buffer-shims": { - "version": "1.0.0", - "bundled": true - }, - "caseless": { - "version": "0.12.0", - "bundled": true, - "optional": true - }, - "co": { - "version": "4.6.0", - "bundled": true, - "optional": true - }, - "code-point-at": { - "version": "1.1.0", - "bundled": true - }, - "combined-stream": { - "version": "1.0.5", - "bundled": true - }, - "concat-map": { - "version": "0.0.1", - "bundled": true - }, - "console-control-strings": { - "version": "1.1.0", - "bundled": true - }, - "core-util-is": { - "version": "1.0.2", - "bundled": true - }, - "cryptiles": { - "version": "2.0.5", - "bundled": true, - "optional": true - }, - "dashdash": { - "version": "1.14.1", - "bundled": true, - "optional": true, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "optional": true - } - } - }, - "debug": { - "version": "2.6.8", - "bundled": true, - "optional": true - }, - "deep-extend": { - "version": "0.4.2", - "bundled": true, - "optional": true - }, - "delayed-stream": { - "version": "1.0.0", - "bundled": true - }, - "delegates": { - "version": "1.0.0", - "bundled": true, - "optional": true - }, - "ecc-jsbn": { - "version": "0.1.1", - "bundled": true, - "optional": true - }, - "extend": { - "version": "3.0.1", - "bundled": true, - "optional": true - }, - "extsprintf": { - "version": "1.0.2", - "bundled": true - }, - "forever-agent": { - "version": "0.6.1", - "bundled": true, - "optional": true - }, - "form-data": { - "version": "2.1.4", - "bundled": true, - "optional": true - }, - "fs.realpath": { - "version": "1.0.0", - "bundled": true - }, - "fstream": { - "version": "1.0.11", - "bundled": true - }, - "fstream-ignore": { - "version": "1.0.5", - "bundled": true, - "optional": true - }, - "gauge": { - "version": "2.7.4", - "bundled": true, - "optional": true - }, - "getpass": { - "version": "0.1.7", - "bundled": true, - "optional": true, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "optional": true - } - } - }, - "glob": { - "version": "7.1.2", - "bundled": true - }, - "graceful-fs": { - "version": "4.1.11", - "bundled": true - }, - "har-schema": { - "version": "1.0.5", - "bundled": true, - "optional": true - }, - "har-validator": { - "version": "4.2.1", - "bundled": true, - "optional": true - }, - "has-unicode": { - "version": "2.0.1", - "bundled": true, - "optional": true - }, - "hawk": { - "version": "3.1.3", - "bundled": true, - "optional": true - }, - "hoek": { - "version": "2.16.3", - "bundled": true - }, - "http-signature": { - "version": "1.1.1", - "bundled": true, - "optional": true - }, - "inflight": { - "version": "1.0.6", - "bundled": true - }, - "inherits": { - "version": "2.0.3", - "bundled": true - }, - "ini": { - "version": "1.3.4", - "bundled": true, - "optional": true - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "bundled": true - }, - "is-typedarray": { - "version": "1.0.0", - "bundled": true, - "optional": true - }, - "isarray": { - "version": "1.0.0", - "bundled": true - }, - "isstream": { - "version": "0.1.2", - "bundled": true, - "optional": true - }, - "jodid25519": { - "version": "1.0.2", - "bundled": true, - "optional": true - }, - "jsbn": { - "version": "0.1.1", - "bundled": true, - "optional": true - }, - "json-schema": { - "version": "0.2.3", - "bundled": true, - "optional": true - }, - "json-stable-stringify": { - "version": "1.0.1", - "bundled": true, - "optional": true - }, - "json-stringify-safe": { - "version": "5.0.1", - "bundled": true, - "optional": true - }, - "jsonify": { - "version": "0.0.0", - "bundled": true, - "optional": true - }, - "jsprim": { - "version": "1.4.0", - "bundled": true, - "optional": true, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "optional": true - } - } - }, - "mime-db": { - "version": "1.27.0", - "bundled": true - }, - "mime-types": { - "version": "2.1.15", - "bundled": true - }, - "minimatch": { - "version": "3.0.4", - "bundled": true - }, - "minimist": { - "version": "0.0.8", - "bundled": true - }, - "mkdirp": { - "version": "0.5.1", - "bundled": true - }, - "ms": { - "version": "2.0.0", - "bundled": true, - "optional": true - }, - "node-pre-gyp": { - "version": "0.6.36", - "bundled": true, - "optional": true - }, - "nopt": { - "version": "4.0.1", - "bundled": true, - "optional": true - }, - "npmlog": { - "version": "4.1.0", - "bundled": true, - "optional": true - }, - "number-is-nan": { - "version": "1.0.1", - "bundled": true - }, - "oauth-sign": { - "version": "0.8.2", - "bundled": true, - "optional": true - }, - "object-assign": { - "version": "4.1.1", - "bundled": true, - "optional": true - }, - "once": { - "version": "1.4.0", - "bundled": true - }, - "os-homedir": { - "version": "1.0.2", - "bundled": true, - "optional": true - }, - "os-tmpdir": { - "version": "1.0.2", - "bundled": true, - "optional": true - }, - "osenv": { - "version": "0.1.4", - "bundled": true, - "optional": true - }, - "path-is-absolute": { - "version": "1.0.1", - "bundled": true - }, - "performance-now": { - "version": "0.2.0", - "bundled": true, - "optional": true - }, - "process-nextick-args": { - "version": "1.0.7", - "bundled": true - }, - "punycode": { - "version": "1.4.1", - "bundled": true, - "optional": true - }, - "qs": { - "version": "6.4.0", - "bundled": true, - "optional": true - }, - "rc": { - "version": "1.2.1", - "bundled": true, - "optional": true, - "dependencies": { - "minimist": { - "version": "1.2.0", - "bundled": true, - "optional": true - } - } - }, - "readable-stream": { - "version": "2.2.9", - "bundled": true - }, - "request": { - "version": "2.81.0", - "bundled": true, - "optional": true - }, - "rimraf": { - "version": "2.6.1", - "bundled": true - }, - "safe-buffer": { - "version": "5.0.1", - "bundled": true - }, - "semver": { - "version": "5.3.0", - "bundled": true, - "optional": true - }, - "set-blocking": { - "version": "2.0.0", - "bundled": true, - "optional": true - }, - "signal-exit": { - "version": "3.0.2", - "bundled": true, - "optional": true - }, - "sntp": { - "version": "1.0.9", - "bundled": true, - "optional": true - }, - "sshpk": { - "version": "1.13.0", - "bundled": true, - "optional": true, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "optional": true - } - } - }, - "string_decoder": { - "version": "1.0.1", - "bundled": true - }, - "string-width": { - "version": "1.0.2", - "bundled": true - }, - "stringstream": { - "version": "0.0.5", - "bundled": true, - "optional": true - }, - "strip-ansi": { - "version": "3.0.1", - "bundled": true - }, - "strip-json-comments": { - "version": "2.0.1", - "bundled": true, - "optional": true - }, - "tar": { - "version": "2.2.1", - "bundled": true - }, - "tar-pack": { - "version": "3.4.0", - "bundled": true, - "optional": true - }, - "tough-cookie": { - "version": "2.3.2", - "bundled": true, - "optional": true - }, - "tunnel-agent": { - "version": "0.6.0", - "bundled": true, - "optional": true - }, - "tweetnacl": { - "version": "0.14.5", - "bundled": true, - "optional": true - }, - "uid-number": { - "version": "0.0.6", - "bundled": true, - "optional": true - }, - "util-deprecate": { - "version": "1.0.2", - "bundled": true - }, - "uuid": { - "version": "3.0.1", - "bundled": true, - "optional": true - }, - "verror": { - "version": "1.3.6", - "bundled": true, - "optional": true - }, - "wide-align": { - "version": "1.1.2", - "bundled": true, - "optional": true - }, - "wrappy": { - "version": "1.0.2", - "bundled": true - } - } - }, "fstream": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.11.tgz", @@ -10642,9 +10114,9 @@ "integrity": "sha1-dc449SvwczxafwwRjYEzSiu19BI=" }, "source-map-loader": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/source-map-loader/-/source-map-loader-0.1.6.tgz", - "integrity": "sha1-wJkD2m1zueU7ftjuUkVZcFHpjpE=", + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/source-map-loader/-/source-map-loader-0.2.1.tgz", + "integrity": "sha1-SBJr6SML1H+tBeRqjDwuPS2r5Qc=", "dependencies": { "async": { "version": "0.9.2", @@ -12196,4 +11668,4 @@ "integrity": "sha1-RCs4+denr3rke/z8NWhz6GFq0bc=" } } -} +} \ No newline at end of file diff --git a/packages/merge-styles/gulpfile.js b/packages/merge-styles/gulpfile.js index b5238c40e78a04..b9d57656a8ab94 100644 --- a/packages/merge-styles/gulpfile.js +++ b/packages/merge-styles/gulpfile.js @@ -29,9 +29,6 @@ build.TypeScriptConfiguration.setTypescriptCompiler(require('typescript')); // Use css modules. build.sass.setConfig({ useCSSModules: true }); -/** Disable webpack. */ -build.webpack.isEnabled = () => false; - let packageFolder = buildConfig.packageFolder || ''; let distFolder = buildConfig.distFolder; diff --git a/packages/merge-styles/package.json b/packages/merge-styles/package.json index d07ab8861974c7..dfebbc83bbaef9 100644 --- a/packages/merge-styles/package.json +++ b/packages/merge-styles/package.json @@ -40,7 +40,8 @@ "react-dom": "^15.4.2", "sinon": "^2.3.2", "source-map-loader": "^0.2.1", - "typescript": "2.4.2" + "typescript": "2.4.2", + "webpack-bundle-analyzer": "^2.2.1" }, "dependencies": { "@uifabric/utilities": ">=4.9.0 <5.0.0", diff --git a/packages/merge-styles/webpack.config.js b/packages/merge-styles/webpack.config.js new file mode 100644 index 00000000000000..a85316c2121340 --- /dev/null +++ b/packages/merge-styles/webpack.config.js @@ -0,0 +1,57 @@ +'use strict'; + +/** Note: this require may need to be fixed to point to the build that exports the gulp-core-build-webpack instance. */ +let build = require('@microsoft/web-library-build'); +let webpackTaskResources = build.webpack.resources; +let webpack = webpackTaskResources.webpack; +let path = require('path'); +let buildConfig = build.getConfig(); +let BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; + +const BUNDLE_NAME = 'merge-styles'; + +let webpackConfig = { + + entry: { + [BUNDLE_NAME]: './lib/index.js' + }, + + output: { + libraryTarget: 'var', + library: 'MergeStyles', + path: path.join(__dirname, buildConfig.distFolder), + publicPath: '/dist/', + filename: `[name].min.js` + }, + + devtool: 'source-map', + + externals: [ + { + 'tslib': { + commonjs: 'tslib', + amd: 'tslib' + } + } + ], + + plugins: [ + new BundleAnalyzerPlugin({ + analyzerMode: 'static', + reportFilename: BUNDLE_NAME + '.stats.html', + openAnalyzer: false + }), + new webpack.DefinePlugin({ + 'process.env.NODE_ENV': JSON.stringify('production') + }), + new webpack.optimize.UglifyJsPlugin({ + minimize: true, + compress: { + warnings: false + } + }) + ] +}; + + +module.exports = webpackConfig; diff --git a/packages/utilities/src/rtl.ts b/packages/utilities/src/rtl.ts index 6c71dfcdc71f23..eaeecb10b399b0 100644 --- a/packages/utilities/src/rtl.ts +++ b/packages/utilities/src/rtl.ts @@ -1,5 +1,4 @@ import { KeyCodes } from './KeyCodes'; -import { getDocument } from './dom'; // Default to undefined so that we initialize on first read. let _isRTL: boolean | undefined; @@ -13,7 +12,7 @@ export function getRTL(): boolean { let isRTL: boolean = _isRTL as boolean; if (isRTL === undefined) { - let doc = getDocument(); + let doc = typeof document === 'undefined' ? undefined : document; if (doc && doc.documentElement) { isRTL = doc.documentElement.getAttribute('dir') === 'rtl'; @@ -29,7 +28,7 @@ export function getRTL(): boolean { * @public */ export function setRTL(isRTL: boolean) { - let doc = getDocument(); + let doc = typeof document === 'undefined' ? undefined : document; if (doc && doc.documentElement) { doc.documentElement.setAttribute('dir', isRTL ? 'rtl' : 'ltr'); From fd670925f64bb963571e0376934fbbc051dbb36b Mon Sep 17 00:00:00 2001 From: David Zearing Date: Wed, 16 Aug 2017 13:51:52 -0700 Subject: [PATCH 03/17] Adding change files. --- .../merge-styles_2017-08-16-20-51.json | 11 +++++++++++ .../experiments/merge-styles_2017-08-16-20-51.json | 11 +++++++++++ .../fabric-website/merge-styles_2017-08-16-20-51.json | 11 +++++++++++ .../utilities/merge-styles_2017-08-16-20-51.json | 11 +++++++++++ .../merge-styles_2017-08-16-20-51.json | 11 +++++++++++ 5 files changed, 55 insertions(+) create mode 100644 common/changes/@uifabric/example-app-base/merge-styles_2017-08-16-20-51.json create mode 100644 common/changes/@uifabric/experiments/merge-styles_2017-08-16-20-51.json create mode 100644 common/changes/@uifabric/fabric-website/merge-styles_2017-08-16-20-51.json create mode 100644 common/changes/@uifabric/utilities/merge-styles_2017-08-16-20-51.json create mode 100644 common/changes/office-ui-fabric-react/merge-styles_2017-08-16-20-51.json diff --git a/common/changes/@uifabric/example-app-base/merge-styles_2017-08-16-20-51.json b/common/changes/@uifabric/example-app-base/merge-styles_2017-08-16-20-51.json new file mode 100644 index 00000000000000..33d339800cbda3 --- /dev/null +++ b/common/changes/@uifabric/example-app-base/merge-styles_2017-08-16-20-51.json @@ -0,0 +1,11 @@ +{ + "changes": [ + { + "packageName": "@uifabric/example-app-base", + "comment": "Updating project dependencies.", + "type": "patch" + } + ], + "packageName": "@uifabric/example-app-base", + "email": "dzearing@microsoft.com" +} \ No newline at end of file diff --git a/common/changes/@uifabric/experiments/merge-styles_2017-08-16-20-51.json b/common/changes/@uifabric/experiments/merge-styles_2017-08-16-20-51.json new file mode 100644 index 00000000000000..7f1199310ce0d2 --- /dev/null +++ b/common/changes/@uifabric/experiments/merge-styles_2017-08-16-20-51.json @@ -0,0 +1,11 @@ +{ + "changes": [ + { + "packageName": "@uifabric/experiments", + "comment": "Updating project dependencies.", + "type": "patch" + } + ], + "packageName": "@uifabric/experiments", + "email": "dzearing@microsoft.com" +} \ No newline at end of file diff --git a/common/changes/@uifabric/fabric-website/merge-styles_2017-08-16-20-51.json b/common/changes/@uifabric/fabric-website/merge-styles_2017-08-16-20-51.json new file mode 100644 index 00000000000000..e1ec4b9d0de7bd --- /dev/null +++ b/common/changes/@uifabric/fabric-website/merge-styles_2017-08-16-20-51.json @@ -0,0 +1,11 @@ +{ + "changes": [ + { + "packageName": "@uifabric/fabric-website", + "comment": "Updating project dependencies.", + "type": "patch" + } + ], + "packageName": "@uifabric/fabric-website", + "email": "dzearing@microsoft.com" +} \ No newline at end of file diff --git a/common/changes/@uifabric/utilities/merge-styles_2017-08-16-20-51.json b/common/changes/@uifabric/utilities/merge-styles_2017-08-16-20-51.json new file mode 100644 index 00000000000000..c3bd0f31ee0918 --- /dev/null +++ b/common/changes/@uifabric/utilities/merge-styles_2017-08-16-20-51.json @@ -0,0 +1,11 @@ +{ + "changes": [ + { + "packageName": "@uifabric/utilities", + "comment": "Minor tweaks to utilities to reduce the graph edges.", + "type": "patch" + } + ], + "packageName": "@uifabric/utilities", + "email": "dzearing@microsoft.com" +} \ No newline at end of file diff --git a/common/changes/office-ui-fabric-react/merge-styles_2017-08-16-20-51.json b/common/changes/office-ui-fabric-react/merge-styles_2017-08-16-20-51.json new file mode 100644 index 00000000000000..43d1c47765ec0d --- /dev/null +++ b/common/changes/office-ui-fabric-react/merge-styles_2017-08-16-20-51.json @@ -0,0 +1,11 @@ +{ + "changes": [ + { + "packageName": "office-ui-fabric-react", + "comment": "Updating project dependencies.", + "type": "patch" + } + ], + "packageName": "office-ui-fabric-react", + "email": "dzearing@microsoft.com" +} \ No newline at end of file From 6d121c96902c33fbe3c47269011a19a55b3a94b2 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Wed, 16 Aug 2017 14:23:09 -0700 Subject: [PATCH 04/17] Adding more tests. --- packages/merge-styles/README.md | 7 ++- packages/merge-styles/api/merge-styles.api.ts | 2 +- packages/merge-styles/src/keyframes.ts | 1 + .../merge-styles/src/mergeStyleSets.test.ts | 50 +++++++++++++++++++ packages/merge-styles/src/server.test.ts | 28 +++++++++++ 5 files changed, 85 insertions(+), 3 deletions(-) create mode 100644 packages/merge-styles/src/mergeStyleSets.test.ts create mode 100644 packages/merge-styles/src/server.test.ts diff --git a/packages/merge-styles/README.md b/packages/merge-styles/README.md index c8c01d896341f2..a9f4488c096ba6 100644 --- a/packages/merge-styles/README.md +++ b/packages/merge-styles/README.md @@ -1,6 +1,9 @@ # [Office UI Fabric - merge-styles](http://dev.office.com/fabric) -The merge-styles library provides a number of utilities for loading styles through javascript. It is designed to make it simple to convert javascript style objects into css classes on the fly. +The merge-styles library provides a number of utilities for loading styles through javascript. It is designed to make it simple to style components through javascript. It generates css rules, rather than using inline styling, to ensure we can use css features like pseudo selectors (:hover) and parent/child selectors (media queries). + +The library was built for speed and size; the entire package is 3.4k gzipped. + The basic idea is to provide a method which can take in one or more style objects css styling javascript objects representing the styles for a given element, and return a single class name. If the same set of styling is passed in, the same name returns and nothing is re-registered. @@ -74,7 +77,7 @@ When building a component, you will need a *style set* map of class names to inj The recommended pattern is to provide the classnames in a separate function, typically in a separate file `ComponentName.classNames.ts`. ```tsx -import { IStyle, mergeStyleSets, memoize } from '@uifabric/merge-styles'; +import { IStyle, mergeStyleSets } from '@uifabric/merge-styles'; export interface IComponentClassNames { root: string; diff --git a/packages/merge-styles/api/merge-styles.api.ts b/packages/merge-styles/api/merge-styles.api.ts index 5e49a39a899887..9858d720f6c22d 100644 --- a/packages/merge-styles/api/merge-styles.api.ts +++ b/packages/merge-styles/api/merge-styles.api.ts @@ -326,7 +326,7 @@ interface IRawStyle extends IRawFontStyle { zoom?: ICSSRule | 'auto' | number | ICSSPercentageRule; } -// @public (undocumented) +// @public export function keyframes(timeline: { [key: string]: {} }): string; // @public diff --git a/packages/merge-styles/src/keyframes.ts b/packages/merge-styles/src/keyframes.ts index 6141f8bca8c7e0..6ebf90a193e3a4 100644 --- a/packages/merge-styles/src/keyframes.ts +++ b/packages/merge-styles/src/keyframes.ts @@ -3,6 +3,7 @@ import { Stylesheet } from './Stylesheet'; import { serializeRuleEntries } from './styleToClassName'; /** + * Registers keyframe definitions. * * @public */ diff --git a/packages/merge-styles/src/mergeStyleSets.test.ts b/packages/merge-styles/src/mergeStyleSets.test.ts new file mode 100644 index 00000000000000..d0f07ea8af4b2e --- /dev/null +++ b/packages/merge-styles/src/mergeStyleSets.test.ts @@ -0,0 +1,50 @@ +import { mergeStyleSets } from './mergeStyleSets'; +import { + Stylesheet, + InjectionMode +} from './Stylesheet'; + +let { expect } = chai; +let _stylesheet: Stylesheet = Stylesheet.getInstance(); + +_stylesheet.setConfig({ injectionMode: InjectionMode.none }); + +describe('mergeStyleSets', () => { + beforeEach(() => { + _stylesheet.reset(); + }); + + it('can merge style sets', () => { + + // tslint:disable-next-line:no-any + let result = mergeStyleSets( + { + root: { background: 'red' }, + a: { background: 'green' } + }, + { + a: { background: 'white' }, + b: { background: 'blue' } + }, + { + root: { + selectors: { + ':hover': { background: 'yellow' } + } + } + } + ); + + expect(result).eqls({ + root: 'css-0', + a: 'css-1', + b: 'css-2' + }); + + expect(_stylesheet.getRules()).equals( + '.css-0{background:red;}.css-0:hover{background:yellow;}' + + '.css-1{background:white;}' + + '.css-2{background:blue;}' + ); + }); +}); \ No newline at end of file diff --git a/packages/merge-styles/src/server.test.ts b/packages/merge-styles/src/server.test.ts new file mode 100644 index 00000000000000..f6203f5910e223 --- /dev/null +++ b/packages/merge-styles/src/server.test.ts @@ -0,0 +1,28 @@ +import { renderStatic } from './server'; +import { + Stylesheet, + InjectionMode +} from './Stylesheet'; +import { + mergeStyleSets +} from './mergeStyleSets'; + +let { expect } = chai; + +describe('staticRender', () => { + it('can render content', () => { + + let { html, css } = renderStatic(() => { + let classNames = mergeStyleSets({ + root: { + background: 'red' + } + }); + + return `
Hello!
`; + }); + + expect(html).equals(`
Hello!
`); + expect(css).equals(`.css-0{background:red;}`); + }); +}); \ No newline at end of file From 9dfbb95b622e02f36b3a0046dd600e8af0826b34 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Wed, 16 Aug 2017 14:28:04 -0700 Subject: [PATCH 05/17] Updating version number. --- packages/merge-styles/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/merge-styles/package.json b/packages/merge-styles/package.json index dfebbc83bbaef9..3faac36e5df533 100644 --- a/packages/merge-styles/package.json +++ b/packages/merge-styles/package.json @@ -1,6 +1,6 @@ { "name": "@uifabric/merge-styles", - "version": "4.9.0", + "version": "0.0.1", "description": "Office UI Fabric style loading utilities.", "main": "lib/index.js", "typings": "lib/index.d.ts", From afa955aead55b1d1d1744c3d9d84445ec8610f83 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Thu, 17 Aug 2017 18:22:28 -0700 Subject: [PATCH 06/17] Updates: remove ALL dependencies bringing the total size down to 2.7k, fix tests, remove async and appendChild features from stylesheet. --- packages/merge-styles/README.md | 20 ++-- packages/merge-styles/api/merge-styles.api.ts | 5 +- packages/merge-styles/gulpfile.js | 8 +- packages/merge-styles/package.json | 9 -- packages/merge-styles/src/IStyle.ts | 2 +- packages/merge-styles/src/Stylesheet.ts | 101 +++++++----------- packages/merge-styles/src/keyframes.ts | 17 +-- packages/merge-styles/src/mergeStyles.test.ts | 18 ++++ packages/merge-styles/src/mergeStyles.ts | 10 +- .../merge-styles/src/styleToClassName.test.ts | 13 ++- packages/merge-styles/src/styleToClassName.ts | 37 ++++--- .../src/transforms/expandQuads.test.ts | 37 ------- .../src/transforms/expandQuads.ts | 31 ------ .../src/transforms/rtlifyRules.test.ts | 3 +- .../src/transforms/rtlifyRules.ts | 18 +++- packages/merge-styles/tsconfig.json | 1 - packages/merge-styles/webpack.config.js | 8 +- 17 files changed, 139 insertions(+), 199 deletions(-) delete mode 100644 packages/merge-styles/src/transforms/expandQuads.test.ts delete mode 100644 packages/merge-styles/src/transforms/expandQuads.ts diff --git a/packages/merge-styles/README.md b/packages/merge-styles/README.md index a9f4488c096ba6..0684b5216dbec9 100644 --- a/packages/merge-styles/README.md +++ b/packages/merge-styles/README.md @@ -2,7 +2,7 @@ The merge-styles library provides a number of utilities for loading styles through javascript. It is designed to make it simple to style components through javascript. It generates css rules, rather than using inline styling, to ensure we can use css features like pseudo selectors (:hover) and parent/child selectors (media queries). -The library was built for speed and size; the entire package is 3.4k gzipped. +The library was built for speed and size; the entire package is 2.7k gzipped. The basic idea is to provide a method which can take in one or more style objects css styling javascript objects representing the styles for a given element, and return a single class name. If the same set of styling is passed in, the same name returns and nothing is re-registered. @@ -154,14 +154,14 @@ export const getClassNames = ( Resolving the class names on every render can be an unwanted expense especially in hot spots where things are rendered frequently. To optimize, we recommend 2 guidelines: -1. For your `getClassNames` function, flatten all input parameters into simple immutable values. This helps the `memoize` utility to cache the results based on the input. +1. For your `getClassNames` function, flatten all input parameters into simple immutable values. This helps the `memoizeFunction` utility to cache the results based on the input. -2. Use the `memoize` function from the `@uifabric/utilities` package to cache the results, given a unique combination of inputs. Example: +2. Use the `memoizeFunction` function from the `@uifabric/utilities` package to cache the results, given a unique combination of inputs. Example: ```tsx -import { memoize } from '@uifabric/utilities'; +import { memoizeFunction } from '@uifabric/utilities'; -export const getClassNames = memoize(( +export const getClassNames = memoizeFunction(( isToggled: boolean ) => { return mergeStyleSet({ @@ -213,6 +213,8 @@ export const getClassNames = () => { ## Server-side rendering +You can import `renderStatic` method from the `/lib/server` entry to render content and extract the css rules that would have been registered, as a string. + Example: ```tsx @@ -223,6 +225,12 @@ let { html, css } = renderStatic(() => { }); ``` -Caveats: +Caveats for server-side rendering (TODOs): * Currently font face definitions and keyframes won't be included in the result. + +* Using the `memoizeFunction` utility may short circuit calling merge-styles APIs to register styles, which may cause the helper here to skip returning css. This can be fixed, but it is currently a known limitation. + +* Until all Fabric components use the merge-styles library, this will only return a subset of the styling. Also a known limitation and work in progress. + +* The rehydration logic has not yet been implemented, so we may run into issues when you rehydrate. diff --git a/packages/merge-styles/api/merge-styles.api.ts b/packages/merge-styles/api/merge-styles.api.ts index 9858d720f6c22d..eb0149664bfef2 100644 --- a/packages/merge-styles/api/merge-styles.api.ts +++ b/packages/merge-styles/api/merge-styles.api.ts @@ -335,7 +335,7 @@ export function mergeStyles(...args: (IStyle | IStyle[])[]): string; // @public export function mergeStyleSets < T extends {} >(...cssSets: T[]): {[P in keyof T]?: string }; -// @public (undocumented) +// @public class Stylesheet { // WARNING: The type "IStyleSheetConfig" needs to be exported by the package (e.g. added to index.ts) constructor(config?: IStyleSheetConfig); @@ -352,8 +352,7 @@ class Stylesheet { // (undocumented) public getRules(): string; // (undocumented) - public insertRule(rule: string, - forceSync: boolean = false): void; + public insertRule(rule: string): void; // (undocumented) public reset(): void; // WARNING: The type "IStyleSheetConfig" needs to be exported by the package (e.g. added to index.ts) diff --git a/packages/merge-styles/gulpfile.js b/packages/merge-styles/gulpfile.js index b9d57656a8ab94..6b32bac66ed9bf 100644 --- a/packages/merge-styles/gulpfile.js +++ b/packages/merge-styles/gulpfile.js @@ -26,8 +26,11 @@ build.tslint.setConfig({ // Configure TypeScript. build.TypeScriptConfiguration.setTypescriptCompiler(require('typescript')); -// Use css modules. -build.sass.setConfig({ useCSSModules: true }); +// Disable unnecessary steps. +build.preCopy.isEnabled = () => false; +build.postCopy.isEnabled = () => false; +build.text.isEnabled = () => false; +build.sass.isEnabled = () => false; let packageFolder = buildConfig.packageFolder || ''; let distFolder = buildConfig.distFolder; @@ -39,4 +42,3 @@ if (isProduction || isClean) { } build.task('tslint', build.tslint); - diff --git a/packages/merge-styles/package.json b/packages/merge-styles/package.json index 3faac36e5df533..64db12826fb3f7 100644 --- a/packages/merge-styles/package.json +++ b/packages/merge-styles/package.json @@ -42,14 +42,5 @@ "source-map-loader": "^0.2.1", "typescript": "2.4.2", "webpack-bundle-analyzer": "^2.2.1" - }, - "dependencies": { - "@uifabric/utilities": ">=4.9.0 <5.0.0", - "prop-types": "^15.5.10", - "tslib": "^1.6.0" - }, - "peerDependencies": { - "react": "^0.14.9 || ^15.0.1-0 || ^16.0.0-0", - "react-dom": "^0.14.9 || ^15.0.1-0 || ^16.0.0-0" } } \ No newline at end of file diff --git a/packages/merge-styles/src/IStyle.ts b/packages/merge-styles/src/IStyle.ts index 8550c60befad6f..9ee5db22535385 100644 --- a/packages/merge-styles/src/IStyle.ts +++ b/packages/merge-styles/src/IStyle.ts @@ -12,7 +12,7 @@ export interface IExtendedRawStyle extends IRawStyle { }; } -export type IStyleBase = IExtendedRawStyle | string | boolean | null | undefined; +export type IStyleBase = IExtendedRawStyle | string | false | null | undefined; /** * IStyleObject extends a raw style objects, but allows selectors to be defined diff --git a/packages/merge-styles/src/Stylesheet.ts b/packages/merge-styles/src/Stylesheet.ts index be0bb3a5a60a4f..6bb886d93d0976 100644 --- a/packages/merge-styles/src/Stylesheet.ts +++ b/packages/merge-styles/src/Stylesheet.ts @@ -1,20 +1,22 @@ -import { GlobalSettings } from '@uifabric/utilities/lib/GlobalSettings'; -import { FabricPerformance } from '@uifabric/utilities/lib/FabricPerformance'; import { IStyle } from './IStyle'; -const STYLESHEET_SETTING = 'stylesheet'; export const enum InjectionMode { none = 0, - insertNode = 1, - appendChild = 2 + insertNode = 1 } export interface IStyleSheetConfig { - async?: boolean; injectionMode?: InjectionMode; } +const STYLESHEET_SETTING = '__stylesheet__'; + +let _stylesheet: Stylesheet; + /** + * Represents the state of styles registered in the page. Abstracts + * the surface for adding styles to the stylesheet, exposes helpers + * for reading the styles registered in server rendered scenarios. * * @public */ @@ -31,7 +33,15 @@ export class Stylesheet { private _classNameToArgs: { [key: string]: any }; public static getInstance(): Stylesheet { - return GlobalSettings.getValue(STYLESHEET_SETTING, () => new Stylesheet()); + // tslint:disable-next-line:no-any + let win: any = typeof window !== 'undefined' ? window : {}; + _stylesheet = win[STYLESHEET_SETTING] as Stylesheet; + + if (!_stylesheet) { + _stylesheet = win[STYLESHEET_SETTING] = new Stylesheet(); + } + + return _stylesheet; } constructor(config?: IStyleSheetConfig) { @@ -71,20 +81,26 @@ export class Stylesheet { } public insertRule( - rule: string, - forceSync: boolean = false + rule: string ): void { - if (this._config.async && !forceSync) { - this._rulesToInsert.push(rule); - if (!this._timerId) { - this._timerId = setTimeout(() => { - this._timerId = 0; - this._insertRule(this._rulesToInsert); - this._rulesToInsert = []; - }, 0); - } - } else { - this._insertRule(rule); + let element = this._getElement(); + let injectionMode = element ? this._config.injectionMode : InjectionMode.none; + + switch (injectionMode) { + case InjectionMode.insertNode: + let { sheet } = element; + + try { + // tslint:disable-next-line:no-any + (sheet as any).insertRule(rule, (sheet as any).cssRules.length); + } catch (e) { + /* no-op on errors */ + } + break; + + default: + this._rules.push(rule); + break; } } @@ -105,51 +121,6 @@ export class Stylesheet { } } - private _insertRule(rule: string | string[]): void { - let element = this._getElement(); - let injectionMode = element ? this._config.injectionMode : InjectionMode.none; - - switch (injectionMode) { - - case InjectionMode.appendChild: - FabricPerformance.measure('appendChild', () => { - element.appendChild(document.createTextNode( - (Array.isArray(rule)) ? rule.join('') : rule - )); - }); - break; - - case InjectionMode.insertNode: - let { sheet } = element; - if (Array.isArray(rule)) { - for (let i = 0; i < rule.length; i++) { - this._insertRule(rule[i]); - } - } else { - FabricPerformance.measure('insertRule', () => { - try { - // tslint:disable-next-line:no-any - (sheet as any).insertRule(rule, (sheet as any).cssRules.length); - } catch (e) { - console.log( - `insertRule failed.\n${e}\nRule: ${rule}` - ); - } - - }); - } - break; - - default: - if (Array.isArray(rule)) { - this._rules = this._rules.concat(rule); - } else { - this._rules.push(rule); - } - break; - } - } - private _getElement(): HTMLStyleElement { if (!this._styleElement) { this._styleElement = document.createElement('style'); diff --git a/packages/merge-styles/src/keyframes.ts b/packages/merge-styles/src/keyframes.ts index 6ebf90a193e3a4..898e31570a0591 100644 --- a/packages/merge-styles/src/keyframes.ts +++ b/packages/merge-styles/src/keyframes.ts @@ -1,4 +1,3 @@ -import { getVendorSettings } from './getVendorSettings'; import { Stylesheet } from './Stylesheet'; import { serializeRuleEntries } from './styleToClassName'; @@ -8,7 +7,6 @@ import { serializeRuleEntries } from './styleToClassName'; * @public */ export function keyframes(timeline: { [key: string]: {} }): string { - let vendorSettings = getVendorSettings(); let stylesheet = Stylesheet.getInstance(); let name = stylesheet.getClassName(); @@ -23,20 +21,7 @@ export function keyframes(timeline: { [key: string]: {} }): string { stylesheet.insertRule(`@keyframes ${name}{${rules}}`); - if (vendorSettings.isWebkit) { - stylesheet.insertRule(`@-webkit-keyframes ${name}{${rules}}`); - } - if (vendorSettings.isMoz) { - stylesheet.insertRule(`@-moz-keyframes ${name}{${rules}}`); - } - - if (vendorSettings.isOpera) { - stylesheet.insertRule(`@-o-keyframes ${name}{${rules}}`); - } - - if (vendorSettings.isMs) { - stylesheet.insertRule(`@-ms-keyframes ${name}{${rules}}`); - } + // If needed later, we would add vendor prefixes here. return name; } diff --git a/packages/merge-styles/src/mergeStyles.test.ts b/packages/merge-styles/src/mergeStyles.test.ts index d1377df05d2439..2f70bcaaa1a16f 100644 --- a/packages/merge-styles/src/mergeStyles.test.ts +++ b/packages/merge-styles/src/mergeStyles.test.ts @@ -26,4 +26,22 @@ describe('mergeStyles', () => { expect(mergeStyles('foo', { background: 'red' })).equals('foo css-0'); expect(_stylesheet.getRules()).equals('.css-0{background:red;}'); }); + + it('can remerge styles', () => { + let className: string = mergeStyles({ background: 'red', color: 'black' }); + let newClassName = mergeStyles(className, { color: 'white' }); + + expect(className).equals('css-0'); + expect(newClassName).equals('css-1'); + expect(_stylesheet.getRules()).equals( + '.css-0{background:red;color:black;}.css-1{background:red;color:white;}' + ); + }); + + it('can normalize margins', () => { + mergeStyles({ margin: '4px' }, { marginRight: '8px' }); + expect(_stylesheet.getRules()).equals( + '.css-0{margin-top:4px;margin-right:8px;margin-bottom:4px;margin-left:4px;}' + ); + }); }); diff --git a/packages/merge-styles/src/mergeStyles.ts b/packages/merge-styles/src/mergeStyles.ts index 23420b248a342d..db9a8f2263f87c 100644 --- a/packages/merge-styles/src/mergeStyles.ts +++ b/packages/merge-styles/src/mergeStyles.ts @@ -1,6 +1,6 @@ import { IStyle } from './IStyle'; import { styleToClassName } from './styleToClassName'; - +import { Stylesheet } from './Stylesheet'; /** * Concatination helper, which can merge class names together. Skips over falsey values. * @@ -9,6 +9,7 @@ import { styleToClassName } from './styleToClassName'; export function mergeStyles(...args: (IStyle | IStyle[])[]): string { let classes: string[] = []; let objects: {}[] = []; + let stylesheet = Stylesheet.getInstance(); function _processArgs(argsList: (IStyle | IStyle[])[]): void { for (let i = 0; i < argsList.length; i++) { @@ -16,7 +17,12 @@ export function mergeStyles(...args: (IStyle | IStyle[])[]): string { if (arg) { if (typeof arg === 'string') { - classes.push(arg); + let translatedArgs = stylesheet.argsFromClassName(arg); + if (translatedArgs) { + objects.push(translatedArgs); + } else { + classes.push(arg); + } } else if (Array.isArray(arg)) { _processArgs(arg); } else if (typeof arg === 'object') { diff --git a/packages/merge-styles/src/styleToClassName.test.ts b/packages/merge-styles/src/styleToClassName.test.ts index d3332c3f69b6fe..25d156d21032c1 100644 --- a/packages/merge-styles/src/styleToClassName.test.ts +++ b/packages/merge-styles/src/styleToClassName.test.ts @@ -1,5 +1,5 @@ import 'es6-map/implement'; -import { setRTL } from '@uifabric/utilities/lib/rtl'; +import { setRTL } from './transforms/rtlifyRules'; import { styleToClassName } from './styleToClassName'; import { InjectionMode, @@ -111,4 +111,15 @@ describe('styleToClassName', () => { expect(_stylesheet.getRules()).equals('.css-0{background:white;}'); }); + it('can expand increased specificity rules', () => { + styleToClassName({ + selectors: { + '&&&': { + background: 'red' + } + } + }); + + expect(_stylesheet.getRules()).equals('.css-0.css-0.css-0{background:red;}'); + }); }); diff --git a/packages/merge-styles/src/styleToClassName.ts b/packages/merge-styles/src/styleToClassName.ts index 026bf184be3869..21781a06cc8ee9 100644 --- a/packages/merge-styles/src/styleToClassName.ts +++ b/packages/merge-styles/src/styleToClassName.ts @@ -2,7 +2,6 @@ import { GlobalSettings } from '@uifabric/utilities/lib/GlobalSettings'; import { rtlifyRules } from './transforms/rtlifyRules'; import { provideUnits } from './transforms/provideUnits'; import { prefixRules } from './transforms/prefixRules'; -import { expandQuads } from './transforms/expandQuads'; import { getVendorSettings } from './getVendorSettings'; import { Stylesheet } from './Stylesheet'; import { IStyle } from './IStyle'; @@ -31,7 +30,6 @@ function toRuleEntry(name: string, value: string): string | undefined { provideUnits(rules); rtlifyRules(rules); prefixRules(rules); - expandQuads(rules); // Stringify the rules. for (let i = 0; i < rules.length; i += 2) { @@ -48,17 +46,6 @@ function getDisplayName(rules?: Map): string | undefined { return rootStyle && (rootStyle as any).displayName; } -/** - * Given an array of objects or strings, iterate through each: - * if string, look up Map. Merge map into current map. - * else if object: - * iterate through each prop: - * if is a selector. - * - * - * edge cases; should :active always have prescidence over :hover? - * ([':hover': {}, ':active': {}], [':hover': {}]) - */ function extractRules( args: IStyle[], rules: Map = new Map(), @@ -104,8 +91,13 @@ function extractRules( } } else { // Else, add the rule to the currentSelector. - // tslint:disable-next-line:no-any - (currentRules as any)[prop] = (arg as any)[prop] as any; + if (prop === 'margin' || prop === 'padding') { + // tslint:disable-next-line:no-any + expandQuads(currentRules, prop, (arg as any)[prop]); + } else { + // tslint:disable-next-line:no-any + (currentRules as any)[prop] = (arg as any)[prop] as any; + } } } } @@ -114,6 +106,18 @@ function extractRules( return rules; } +function expandQuads( + currentRules: { [key: string]: string }, + name: string, + value: string +): void { + let parts = value.split(' '); + currentRules[name + 'Top'] = parts[0]; + currentRules[name + 'Right'] = parts[1] || parts[0]; + currentRules[name + 'Bottom'] = parts[2] || parts[0]; + currentRules[name + 'Left'] = parts[3] || parts[1] || parts[0]; +} + function serializeRules(rules: Map): string | undefined { let serialized: string[] = []; let hasProps = false; @@ -168,12 +172,13 @@ export function styleToClassName(...args: IStyle[]): string { let rulesToInsert: string = serializeRuleEntries(rules.get(selector) as {}); if (rulesToInsert) { - selector = selector.replace('&', `.${className}`); + selector = selector.replace(/\&/g, `.${className}`); stylesheet.insertRule(`${selector}{${rulesToInsert}}`); } selector = ruleSelectors.next().value; } } } + return className; } diff --git a/packages/merge-styles/src/transforms/expandQuads.test.ts b/packages/merge-styles/src/transforms/expandQuads.test.ts deleted file mode 100644 index 65a4f7acacd9ed..00000000000000 --- a/packages/merge-styles/src/transforms/expandQuads.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { expandQuads } from './expandQuads'; - -import { expect } from 'chai'; - -describe('expandQuads', () => { - it('can expand margins and paddings', () => { - let rules = ['margin', '0px 1px 2px 3px']; - - expandQuads(rules); - - expect(rules).eqls([ - 'marginTop', - '0px', - 'marginRight', - '1px', - 'marginBottom', - '2px', - 'marginLeft', - '3px' - ]); - - rules = ['padding', '0px 1px 2px 3px']; - - expandQuads(rules); - - expect(rules).eqls([ - 'paddingTop', - '0px', - 'paddingRight', - '1px', - 'paddingBottom', - '2px', - 'paddingLeft', - '3px' - ]); - }); -}); diff --git a/packages/merge-styles/src/transforms/expandQuads.ts b/packages/merge-styles/src/transforms/expandQuads.ts deleted file mode 100644 index 1788c6eaf6d2ca..00000000000000 --- a/packages/merge-styles/src/transforms/expandQuads.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { IVendorSettings } from '../getVendorSettings'; - -export function expandQuads( - rulePairs: string[], - vendorSettings?: IVendorSettings -): void { - for (let nameIndex = 0; nameIndex < rulePairs.length; nameIndex += 2) { - let name = rulePairs[nameIndex]; - - switch (name) { - case 'margin': - case 'padding': - let parts = rulePairs[nameIndex + 1].split(' '); - - rulePairs.splice( - nameIndex, - 2, - name + 'Top', - parts[0], - name + 'Right', - parts[1] || parts[0], - name + 'Bottom', - parts[2] || parts[0], - name + 'Left', - parts[3] || parts[1] || parts[0], - ); - - nameIndex += 6; - } - } -} diff --git a/packages/merge-styles/src/transforms/rtlifyRules.test.ts b/packages/merge-styles/src/transforms/rtlifyRules.test.ts index b524f17a9cb87f..9c31b6ff071128 100644 --- a/packages/merge-styles/src/transforms/rtlifyRules.test.ts +++ b/packages/merge-styles/src/transforms/rtlifyRules.test.ts @@ -1,5 +1,4 @@ -import { setRTL } from '@uifabric/utilities/lib/rtl'; -import { rtlifyRules } from './rtlifyRules'; +import { setRTL, rtlifyRules } from './rtlifyRules'; let { expect } = chai; diff --git a/packages/merge-styles/src/transforms/rtlifyRules.ts b/packages/merge-styles/src/transforms/rtlifyRules.ts index 9d445bfb52da1f..02b556ff17af97 100644 --- a/packages/merge-styles/src/transforms/rtlifyRules.ts +++ b/packages/merge-styles/src/transforms/rtlifyRules.ts @@ -1,5 +1,3 @@ -import { getRTL } from '@uifabric/utilities/lib/rtl'; - const _nameReplacements: { [key: string]: string } = { 'left': 'right', 'right': 'left' @@ -13,6 +11,22 @@ const _valueReplacements: { [key: string]: string } = { const NO_FLIP = 'noflip'; +let _rtl = getRTL(); + +export function setRTL(isRTL: boolean): void { + _rtl = isRTL; +} +export function getRTL(): boolean { + if (_rtl === undefined) { + _rtl = ( + typeof document !== undefined && + !!document.documentElement && + document.documentElement.getAttribute('dir') === 'rtl' + ); + } + return _rtl; +} + export function rtlifyRules(rulePairs: string[]): string[] { if (getRTL()) { for (let nameIndex = 0, valueIndex = 1; nameIndex < rulePairs.length; nameIndex += 2, valueIndex += 2) { diff --git a/packages/merge-styles/tsconfig.json b/packages/merge-styles/tsconfig.json index fb6d04adec19ba..41bca66eb43b29 100644 --- a/packages/merge-styles/tsconfig.json +++ b/packages/merge-styles/tsconfig.json @@ -10,7 +10,6 @@ "declaration": true, "sourceMap": true, "experimentalDecorators": true, - "importHelpers": true, "noImplicitAny": true, "strictNullChecks": true, "forceConsistentCasingInFileNames": true, diff --git a/packages/merge-styles/webpack.config.js b/packages/merge-styles/webpack.config.js index a85316c2121340..0806676d047e04 100644 --- a/packages/merge-styles/webpack.config.js +++ b/packages/merge-styles/webpack.config.js @@ -28,10 +28,10 @@ let webpackConfig = { externals: [ { - 'tslib': { - commonjs: 'tslib', - amd: 'tslib' - } + // 'tslib': { + // commonjs: 'tslib', + // amd: 'tslib' + // } } ], From 404ec5976c0eccce261483091e7291646d752ce3 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Thu, 17 Aug 2017 18:42:22 -0700 Subject: [PATCH 07/17] Fixing for loops and readme and strict mode. --- packages/merge-styles/README.md | 1 - packages/merge-styles/src/concatStyleSets.ts | 6 ++---- packages/merge-styles/src/keyframes.ts | 2 +- packages/merge-styles/src/mergeStyleSets.ts | 2 +- packages/merge-styles/src/mergeStyles.ts | 5 ++--- packages/merge-styles/src/styleToClassName.ts | 4 +--- packages/merge-styles/tsconfig.json | 2 +- 7 files changed, 8 insertions(+), 14 deletions(-) diff --git a/packages/merge-styles/README.md b/packages/merge-styles/README.md index 0684b5216dbec9..cc59a13bc8d442 100644 --- a/packages/merge-styles/README.md +++ b/packages/merge-styles/README.md @@ -4,7 +4,6 @@ The merge-styles library provides a number of utilities for loading styles throu The library was built for speed and size; the entire package is 2.7k gzipped. - The basic idea is to provide a method which can take in one or more style objects css styling javascript objects representing the styles for a given element, and return a single class name. If the same set of styling is passed in, the same name returns and nothing is re-registered. This has a number of benefits over traditional build time staticly produced css: diff --git a/packages/merge-styles/src/concatStyleSets.ts b/packages/merge-styles/src/concatStyleSets.ts index 78a43232d66e4d..6b8f5198646023 100644 --- a/packages/merge-styles/src/concatStyleSets.ts +++ b/packages/merge-styles/src/concatStyleSets.ts @@ -7,11 +7,9 @@ import { IStyleSet } from './IStyleSet'; export function concatStyleSets(...args: (T | false | null | undefined)[]): T { let mergedSet: IStyleSet = {}; - for (let i = 0; i < args.length; i++) { - let currentSet = args[i]; - + for (const currentSet of args) { if (currentSet) { - for (let prop in currentSet) { + for (const prop in currentSet) { if (currentSet.hasOwnProperty(prop)) { let mergedValue = mergedSet[prop]; let currentValue = currentSet[prop]; diff --git a/packages/merge-styles/src/keyframes.ts b/packages/merge-styles/src/keyframes.ts index 898e31570a0591..c16c44d5d1ed24 100644 --- a/packages/merge-styles/src/keyframes.ts +++ b/packages/merge-styles/src/keyframes.ts @@ -12,7 +12,7 @@ export function keyframes(timeline: { [key: string]: {} }): string { let rulesArray: string[] = []; - for (let prop in timeline) { + for (const prop in timeline) { if (timeline.hasOwnProperty(prop)) { rulesArray.push(prop, ' {', serializeRuleEntries(timeline[prop]), '}'); } diff --git a/packages/merge-styles/src/mergeStyleSets.ts b/packages/merge-styles/src/mergeStyleSets.ts index c9929aaf011a5a..c75644f214cc07 100644 --- a/packages/merge-styles/src/mergeStyleSets.ts +++ b/packages/merge-styles/src/mergeStyleSets.ts @@ -17,7 +17,7 @@ export function mergeStyleSets( if (cssSets.length > 1) { cssSet = concatStyleSets(...cssSets); } - for (let prop in cssSet) { + for (const prop in cssSet) { if (cssSet.hasOwnProperty(prop)) { classNameSet[prop] = mergeStyles(cssSet[prop] as IStyle); } diff --git a/packages/merge-styles/src/mergeStyles.ts b/packages/merge-styles/src/mergeStyles.ts index db9a8f2263f87c..ec5be9ed06565c 100644 --- a/packages/merge-styles/src/mergeStyles.ts +++ b/packages/merge-styles/src/mergeStyles.ts @@ -1,6 +1,7 @@ import { IStyle } from './IStyle'; import { styleToClassName } from './styleToClassName'; import { Stylesheet } from './Stylesheet'; + /** * Concatination helper, which can merge class names together. Skips over falsey values. * @@ -12,9 +13,7 @@ export function mergeStyles(...args: (IStyle | IStyle[])[]): string { let stylesheet = Stylesheet.getInstance(); function _processArgs(argsList: (IStyle | IStyle[])[]): void { - for (let i = 0; i < argsList.length; i++) { - let arg = argsList[i]; - + for (const arg of argsList) { if (arg) { if (typeof arg === 'string') { let translatedArgs = stylesheet.argsFromClassName(arg); diff --git a/packages/merge-styles/src/styleToClassName.ts b/packages/merge-styles/src/styleToClassName.ts index 21781a06cc8ee9..c6238601362651 100644 --- a/packages/merge-styles/src/styleToClassName.ts +++ b/packages/merge-styles/src/styleToClassName.ts @@ -59,9 +59,7 @@ function extractRules( rules.set(currentSelector, currentRules); } - for (let i = 0; i < args.length; i++) { - const arg: IStyle = args[i]; - + for (const arg of args) { // If the arg is a string, we need to look up the class map and merge. if (typeof arg === 'string') { let expandedRules = stylesheet.argsFromClassName(arg); diff --git a/packages/merge-styles/tsconfig.json b/packages/merge-styles/tsconfig.json index 41bca66eb43b29..55327985569192 100644 --- a/packages/merge-styles/tsconfig.json +++ b/packages/merge-styles/tsconfig.json @@ -11,7 +11,7 @@ "sourceMap": true, "experimentalDecorators": true, "noImplicitAny": true, - "strictNullChecks": true, + "strict": true, "forceConsistentCasingInFileNames": true, "moduleResolution": "node", "types": [ From 796dfcfec5a7d1e12928f2560dc8ee1b09c6d039 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Thu, 17 Aug 2017 19:02:35 -0700 Subject: [PATCH 08/17] const updates. --- packages/merge-styles/src/Stylesheet.ts | 10 ++--- .../merge-styles/src/concatStyleSets.test.ts | 4 +- packages/merge-styles/src/concatStyleSets.ts | 6 +-- packages/merge-styles/src/fontFace.test.ts | 4 +- .../merge-styles/src/getVendorSettings.ts | 6 +-- packages/merge-styles/src/keyframes.ts | 8 ++-- .../merge-styles/src/mergeStyleSets.test.ts | 6 +-- packages/merge-styles/src/mergeStyleSets.ts | 2 +- packages/merge-styles/src/mergeStyles.test.ts | 9 ++-- packages/merge-styles/src/mergeStyles.ts | 8 ++-- packages/merge-styles/src/server.test.ts | 6 +-- packages/merge-styles/src/server.ts | 2 +- .../merge-styles/src/styleToClassName.test.ts | 12 +++--- packages/merge-styles/src/styleToClassName.ts | 41 +++++++++---------- .../src/transforms/prefixRules.test.ts | 8 ++-- .../src/transforms/prefixRules.ts | 8 ++-- .../src/transforms/provideUnits.test.ts | 8 ++-- .../src/transforms/provideUnits.ts | 2 +- .../src/transforms/rtlifyRules.test.ts | 4 +- .../src/transforms/rtlifyRules.ts | 10 ++--- 20 files changed, 82 insertions(+), 82 deletions(-) diff --git a/packages/merge-styles/src/Stylesheet.ts b/packages/merge-styles/src/Stylesheet.ts index 6bb886d93d0976..20cbe249c1e313 100644 --- a/packages/merge-styles/src/Stylesheet.ts +++ b/packages/merge-styles/src/Stylesheet.ts @@ -34,7 +34,7 @@ export class Stylesheet { public static getInstance(): Stylesheet { // tslint:disable-next-line:no-any - let win: any = typeof window !== 'undefined' ? window : {}; + const win: any = typeof window !== 'undefined' ? window : {}; _stylesheet = win[STYLESHEET_SETTING] as Stylesheet; if (!_stylesheet) { @@ -62,7 +62,7 @@ export class Stylesheet { } public getClassName(displayName?: string): string { - let prefix = displayName || 'css'; + const prefix = displayName || 'css'; return `${prefix}-${this._counter++}`; } @@ -83,12 +83,12 @@ export class Stylesheet { public insertRule( rule: string ): void { - let element = this._getElement(); - let injectionMode = element ? this._config.injectionMode : InjectionMode.none; + const element = this._getElement(); + const injectionMode = element ? this._config.injectionMode : InjectionMode.none; switch (injectionMode) { case InjectionMode.insertNode: - let { sheet } = element; + const { sheet } = element; try { // tslint:disable-next-line:no-any diff --git a/packages/merge-styles/src/concatStyleSets.test.ts b/packages/merge-styles/src/concatStyleSets.test.ts index bd4f46fa5120ed..b94b7e481636e2 100644 --- a/packages/merge-styles/src/concatStyleSets.test.ts +++ b/packages/merge-styles/src/concatStyleSets.test.ts @@ -1,12 +1,12 @@ import { concatStyleSets } from './concatStyleSets'; -let { expect } = chai; +const { expect } = chai; describe('concatStyleSets', () => { it('can concat style sets', () => { // tslint:disable-next-line:no-any - let result = concatStyleSets( + const result = concatStyleSets( { root: { background: 'red' }, a: { background: 'green' } diff --git a/packages/merge-styles/src/concatStyleSets.ts b/packages/merge-styles/src/concatStyleSets.ts index 6b8f5198646023..51e79176e3c19f 100644 --- a/packages/merge-styles/src/concatStyleSets.ts +++ b/packages/merge-styles/src/concatStyleSets.ts @@ -5,14 +5,14 @@ import { IStyleSet } from './IStyleSet'; * @public */ export function concatStyleSets(...args: (T | false | null | undefined)[]): T { - let mergedSet: IStyleSet = {}; + const mergedSet: IStyleSet = {}; for (const currentSet of args) { if (currentSet) { for (const prop in currentSet) { if (currentSet.hasOwnProperty(prop)) { - let mergedValue = mergedSet[prop]; - let currentValue = currentSet[prop]; + const mergedValue = mergedSet[prop]; + const currentValue = currentSet[prop]; if (mergedValue === undefined) { mergedSet[prop] = currentValue; diff --git a/packages/merge-styles/src/fontFace.test.ts b/packages/merge-styles/src/fontFace.test.ts index ac5cbf2997b55a..722e1340be8c0d 100644 --- a/packages/merge-styles/src/fontFace.test.ts +++ b/packages/merge-styles/src/fontFace.test.ts @@ -4,8 +4,8 @@ import { InjectionMode } from './Stylesheet'; -let { expect } = chai; -let _stylesheet: Stylesheet = Stylesheet.getInstance(); +const { expect } = chai; +const _stylesheet: Stylesheet = Stylesheet.getInstance(); _stylesheet.setConfig({ injectionMode: InjectionMode.none }); diff --git a/packages/merge-styles/src/getVendorSettings.ts b/packages/merge-styles/src/getVendorSettings.ts index fdc77502458ab7..64efe9b5b4a03d 100644 --- a/packages/merge-styles/src/getVendorSettings.ts +++ b/packages/merge-styles/src/getVendorSettings.ts @@ -9,9 +9,9 @@ let _vendorSettings: IVendorSettings | undefined; export function getVendorSettings(): IVendorSettings { if (!_vendorSettings) { - let doc = typeof document !== 'undefined' ? document : undefined; - let nav = typeof navigator !== 'undefined' ? navigator : undefined; - let userAgent = nav ? nav.userAgent.toLowerCase() : undefined; + const doc = typeof document !== 'undefined' ? document : undefined; + const nav = typeof navigator !== 'undefined' ? navigator : undefined; + const userAgent = nav ? nav.userAgent.toLowerCase() : undefined; if (!doc) { _vendorSettings = { diff --git a/packages/merge-styles/src/keyframes.ts b/packages/merge-styles/src/keyframes.ts index c16c44d5d1ed24..e0ab28ec5c02fb 100644 --- a/packages/merge-styles/src/keyframes.ts +++ b/packages/merge-styles/src/keyframes.ts @@ -7,17 +7,17 @@ import { serializeRuleEntries } from './styleToClassName'; * @public */ export function keyframes(timeline: { [key: string]: {} }): string { - let stylesheet = Stylesheet.getInstance(); - let name = stylesheet.getClassName(); + const stylesheet = Stylesheet.getInstance(); + const name = stylesheet.getClassName(); - let rulesArray: string[] = []; + const rulesArray: string[] = []; for (const prop in timeline) { if (timeline.hasOwnProperty(prop)) { rulesArray.push(prop, ' {', serializeRuleEntries(timeline[prop]), '}'); } } - let rules = rulesArray.join(''); + const rules = rulesArray.join(''); stylesheet.insertRule(`@keyframes ${name}{${rules}}`); diff --git a/packages/merge-styles/src/mergeStyleSets.test.ts b/packages/merge-styles/src/mergeStyleSets.test.ts index d0f07ea8af4b2e..3736931fb58c8a 100644 --- a/packages/merge-styles/src/mergeStyleSets.test.ts +++ b/packages/merge-styles/src/mergeStyleSets.test.ts @@ -4,8 +4,8 @@ import { InjectionMode } from './Stylesheet'; -let { expect } = chai; -let _stylesheet: Stylesheet = Stylesheet.getInstance(); +const { expect } = chai; +const _stylesheet: Stylesheet = Stylesheet.getInstance(); _stylesheet.setConfig({ injectionMode: InjectionMode.none }); @@ -17,7 +17,7 @@ describe('mergeStyleSets', () => { it('can merge style sets', () => { // tslint:disable-next-line:no-any - let result = mergeStyleSets( + const result = mergeStyleSets( { root: { background: 'red' }, a: { background: 'green' } diff --git a/packages/merge-styles/src/mergeStyleSets.ts b/packages/merge-styles/src/mergeStyleSets.ts index c75644f214cc07..16dbcafff407c0 100644 --- a/packages/merge-styles/src/mergeStyleSets.ts +++ b/packages/merge-styles/src/mergeStyleSets.ts @@ -11,7 +11,7 @@ import { IStyle } from './IStyle'; export function mergeStyleSets( ...cssSets: T[] ): {[P in keyof T]?: string } { - let classNameSet: {[P in keyof T]?: string } = {}; + const classNameSet: {[P in keyof T]?: string } = {}; let cssSet = cssSets[0]; if (cssSets.length > 1) { diff --git a/packages/merge-styles/src/mergeStyles.test.ts b/packages/merge-styles/src/mergeStyles.test.ts index 2f70bcaaa1a16f..a251bbe9e12453 100644 --- a/packages/merge-styles/src/mergeStyles.test.ts +++ b/packages/merge-styles/src/mergeStyles.test.ts @@ -4,8 +4,8 @@ import { InjectionMode } from './Stylesheet'; -let { expect } = chai; -let _stylesheet: Stylesheet = Stylesheet.getInstance(); +const { expect } = chai; +const _stylesheet: Stylesheet = Stylesheet.getInstance(); _stylesheet.setConfig({ injectionMode: InjectionMode.none }); @@ -28,8 +28,8 @@ describe('mergeStyles', () => { }); it('can remerge styles', () => { - let className: string = mergeStyles({ background: 'red', color: 'black' }); - let newClassName = mergeStyles(className, { color: 'white' }); + const className: string = mergeStyles({ background: 'red', color: 'black' }); + const newClassName = mergeStyles(className, { color: 'white' }); expect(className).equals('css-0'); expect(newClassName).equals('css-1'); @@ -44,4 +44,5 @@ describe('mergeStyles', () => { '.css-0{margin-top:4px;margin-right:8px;margin-bottom:4px;margin-left:4px;}' ); }); + }); diff --git a/packages/merge-styles/src/mergeStyles.ts b/packages/merge-styles/src/mergeStyles.ts index ec5be9ed06565c..1f9beef45bca3b 100644 --- a/packages/merge-styles/src/mergeStyles.ts +++ b/packages/merge-styles/src/mergeStyles.ts @@ -8,15 +8,15 @@ import { Stylesheet } from './Stylesheet'; * @public */ export function mergeStyles(...args: (IStyle | IStyle[])[]): string { - let classes: string[] = []; - let objects: {}[] = []; - let stylesheet = Stylesheet.getInstance(); + const classes: string[] = []; + const objects: {}[] = []; + const stylesheet = Stylesheet.getInstance(); function _processArgs(argsList: (IStyle | IStyle[])[]): void { for (const arg of argsList) { if (arg) { if (typeof arg === 'string') { - let translatedArgs = stylesheet.argsFromClassName(arg); + const translatedArgs = stylesheet.argsFromClassName(arg); if (translatedArgs) { objects.push(translatedArgs); } else { diff --git a/packages/merge-styles/src/server.test.ts b/packages/merge-styles/src/server.test.ts index f6203f5910e223..cd5ee2480cdf44 100644 --- a/packages/merge-styles/src/server.test.ts +++ b/packages/merge-styles/src/server.test.ts @@ -7,13 +7,13 @@ import { mergeStyleSets } from './mergeStyleSets'; -let { expect } = chai; +const { expect } = chai; describe('staticRender', () => { it('can render content', () => { - let { html, css } = renderStatic(() => { - let classNames = mergeStyleSets({ + const { html, css } = renderStatic(() => { + const classNames = mergeStyleSets({ root: { background: 'red' } diff --git a/packages/merge-styles/src/server.ts b/packages/merge-styles/src/server.ts index 26882cb6715b19..6039007617198b 100644 --- a/packages/merge-styles/src/server.ts +++ b/packages/merge-styles/src/server.ts @@ -3,7 +3,7 @@ import { InjectionMode, Stylesheet } from './Stylesheet'; export function renderStatic( onRender: () => string ): { html: string, css: string } { - let stylesheet = Stylesheet.getInstance(); + const stylesheet = Stylesheet.getInstance(); stylesheet.setConfig({ injectionMode: InjectionMode.none diff --git a/packages/merge-styles/src/styleToClassName.test.ts b/packages/merge-styles/src/styleToClassName.test.ts index 25d156d21032c1..ba11f25e031aad 100644 --- a/packages/merge-styles/src/styleToClassName.test.ts +++ b/packages/merge-styles/src/styleToClassName.test.ts @@ -6,8 +6,8 @@ import { Stylesheet } from './Stylesheet'; -let { expect } = chai; -let _stylesheet: Stylesheet = Stylesheet.getInstance(); +const { expect } = chai; +const _stylesheet: Stylesheet = Stylesheet.getInstance(); _stylesheet.setConfig({ injectionMode: InjectionMode.none }); @@ -34,7 +34,7 @@ describe('styleToClassName', () => { }); it('can register pseudo selectors', () => { - let className = styleToClassName({ + const className = styleToClassName({ selectors: { ':hover': { background: 'red' } } @@ -45,7 +45,7 @@ describe('styleToClassName', () => { }); it('can register parent and sibling selectors', () => { - let className = styleToClassName({ + const className = styleToClassName({ selectors: { '& .child': { background: 'red' }, '.parent &': { background: 'green' } @@ -96,8 +96,8 @@ describe('styleToClassName', () => { }); it('can expand previously defined rules', () => { - let className = styleToClassName({ background: 'red' }); - let newClassName = styleToClassName(className, { color: 'white' }); + const className = styleToClassName({ background: 'red' }); + const newClassName = styleToClassName(className, { color: 'white' }); expect(newClassName).equals('css-1'); expect(_stylesheet.getRules()).equals('.css-0{background:red;}.css-1{background:red;color:white;}'); diff --git a/packages/merge-styles/src/styleToClassName.ts b/packages/merge-styles/src/styleToClassName.ts index c6238601362651..45dc4292d76701 100644 --- a/packages/merge-styles/src/styleToClassName.ts +++ b/packages/merge-styles/src/styleToClassName.ts @@ -4,7 +4,7 @@ import { provideUnits } from './transforms/provideUnits'; import { prefixRules } from './transforms/prefixRules'; import { getVendorSettings } from './getVendorSettings'; import { Stylesheet } from './Stylesheet'; -import { IStyle } from './IStyle'; +import { IStyle, IExtendedRawStyle } from './IStyle'; const DISPLAY_NAME = 'displayName'; @@ -19,12 +19,12 @@ function toRuleEntry(name: string, value: string): string | undefined { } // Kebab case the rule. - let rules: string[] = [ + const rules: string[] = [ name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(), value ]; - let ruleEntries: string[] = []; + const ruleEntries: string[] = []; // Apply transforms. provideUnits(rules); @@ -40,10 +40,9 @@ function toRuleEntry(name: string, value: string): string | undefined { } function getDisplayName(rules?: Map): string | undefined { - let rootStyle: IStyle = rules && rules.get('&'); + const rootStyle: IStyle = rules && rules.get('&'); - // tslint:disable-next-line:no-any - return rootStyle && (rootStyle as any).displayName; + return rootStyle ? (rootStyle as IExtendedRawStyle).displayName : undefined; } function extractRules( @@ -51,7 +50,7 @@ function extractRules( rules: Map = new Map(), currentSelector: string = '&' ): Map { - let stylesheet = Stylesheet.getInstance(); + const stylesheet = Stylesheet.getInstance(); let currentRules: {} | undefined = rules.get(currentSelector); if (!currentRules) { @@ -62,7 +61,7 @@ function extractRules( for (const arg of args) { // If the arg is a string, we need to look up the class map and merge. if (typeof arg === 'string') { - let expandedRules = stylesheet.argsFromClassName(arg); + const expandedRules = stylesheet.argsFromClassName(arg); if (expandedRules) { extractRules(expandedRules, rules); @@ -72,14 +71,14 @@ function extractRules( extractRules(arg, rules, currentSelector); } else { // tslint:disable-next-line:no-any - for (let prop in (arg as any)) { + for (const prop in (arg as any)) { if (prop === 'selectors') { // tslint:disable-next-line:no-any - let selectors: { [key: string]: IStyle } = (arg as any).selectors; + const selectors: { [key: string]: IStyle } = (arg as any).selectors; for (let newSelector in selectors) { if (selectors.hasOwnProperty(newSelector)) { - let selectorValue = selectors[newSelector]; + const selectorValue = selectors[newSelector]; if (newSelector.indexOf('&') < 0) { newSelector = currentSelector + newSelector; @@ -109,7 +108,7 @@ function expandQuads( name: string, value: string ): void { - let parts = value.split(' '); + const parts = value.split(' '); currentRules[name + 'Top'] = parts[0]; currentRules[name + 'Right'] = parts[1] || parts[0]; currentRules[name + 'Bottom'] = parts[2] || parts[0]; @@ -117,13 +116,13 @@ function expandQuads( } function serializeRules(rules: Map): string | undefined { - let serialized: string[] = []; + const serialized: string[] = []; let hasProps = false; rules.forEach((ruleEntries: { [key: string]: string }, selector: string): void => { serialized.push(selector); - for (let propName in ruleEntries) { + for (const propName in ruleEntries) { if (ruleEntries.hasOwnProperty(propName)) { hasProps = true; serialized.push(propName); @@ -136,10 +135,10 @@ function serializeRules(rules: Map): string | undefined { } export function serializeRuleEntries(ruleEntries: { [key: string]: string }): string { - let allEntries: string[] = []; + const allEntries: string[] = []; if (ruleEntries) { - for (let entry in ruleEntries) { + for (const entry in ruleEntries) { if (ruleEntries.hasOwnProperty(entry)) { allEntries.push(toRuleEntry(entry, ruleEntries[entry])!); } @@ -150,12 +149,12 @@ export function serializeRuleEntries(ruleEntries: { [key: string]: string }): st } export function styleToClassName(...args: IStyle[]): string { - let rules: Map = extractRules(args); - let key = serializeRules(rules); + const rules: Map = extractRules(args); + const key = serializeRules(rules); let className = ''; if (key) { - let stylesheet = Stylesheet.getInstance(); + const stylesheet = Stylesheet.getInstance(); className = stylesheet.classNameFromKey(key)!; @@ -163,11 +162,11 @@ export function styleToClassName(...args: IStyle[]): string { className = stylesheet.getClassName(getDisplayName(rules)); stylesheet.cacheClassName(className, key, args); - let ruleSelectors = rules.keys(); + const ruleSelectors = rules.keys(); let selector = ruleSelectors.next().value; while (selector) { - let rulesToInsert: string = serializeRuleEntries(rules.get(selector) as {}); + const rulesToInsert: string = serializeRuleEntries(rules.get(selector) as {}); if (rulesToInsert) { selector = selector.replace(/\&/g, `.${className}`); diff --git a/packages/merge-styles/src/transforms/prefixRules.test.ts b/packages/merge-styles/src/transforms/prefixRules.test.ts index 577aa093798b11..09c86a2bcb40f1 100644 --- a/packages/merge-styles/src/transforms/prefixRules.test.ts +++ b/packages/merge-styles/src/transforms/prefixRules.test.ts @@ -13,7 +13,7 @@ describe('prefixRules', () => { it('can provide translate webkit rules', () => { AUTO_TRANSLATED_RULES.forEach((rule: string) => { - let rules = [rule, 'none']; + const rules = [rule, 'none']; setVendorSettings({ isWebkit: true }); prefixRules(rules); @@ -27,7 +27,7 @@ describe('prefixRules', () => { it('can provide translate moz rules', () => { AUTO_TRANSLATED_RULES.forEach((rule: string) => { - let rules = [rule, 'none']; + const rules = [rule, 'none']; setVendorSettings({ isMoz: true }); prefixRules(rules); @@ -40,7 +40,7 @@ describe('prefixRules', () => { it('can provide translate ms rules', () => { AUTO_TRANSLATED_RULES.forEach((rule: string) => { - let rules = [rule, 'none']; + const rules = [rule, 'none']; setVendorSettings({ isMs: true }); prefixRules(rules); @@ -53,7 +53,7 @@ describe('prefixRules', () => { it('can provide translate opera rules', () => { AUTO_TRANSLATED_RULES.forEach((rule: string) => { - let rules = [rule, 'none']; + const rules = [rule, 'none']; setVendorSettings({ isOpera: true }); prefixRules(rules); diff --git a/packages/merge-styles/src/transforms/prefixRules.ts b/packages/merge-styles/src/transforms/prefixRules.ts index 4069080998444b..5218488c1f902c 100644 --- a/packages/merge-styles/src/transforms/prefixRules.ts +++ b/packages/merge-styles/src/transforms/prefixRules.ts @@ -1,17 +1,17 @@ import { getVendorSettings } from '../getVendorSettings'; -let autoPrefixNames: { [key: string]: number } = { +const autoPrefixNames: { [key: string]: number } = { 'user-select': 1 }; export function prefixRules( rulePairs: string[] ): void { - let vendorSettings = getVendorSettings(); + const vendorSettings = getVendorSettings(); for (let nameIndex = 0, valueIndex = 1; nameIndex < rulePairs.length; nameIndex += 2, valueIndex += 2) { - let name = rulePairs[nameIndex]; - let value = rulePairs[valueIndex]; + const name = rulePairs[nameIndex]; + const value = rulePairs[valueIndex]; if (autoPrefixNames[name]) { if (vendorSettings.isWebkit) { diff --git a/packages/merge-styles/src/transforms/provideUnits.test.ts b/packages/merge-styles/src/transforms/provideUnits.test.ts index e356d7a90b8bfd..1aef330b9d0e38 100644 --- a/packages/merge-styles/src/transforms/provideUnits.test.ts +++ b/packages/merge-styles/src/transforms/provideUnits.test.ts @@ -4,14 +4,14 @@ import { expect } from 'chai'; describe('provideUnits', () => { it('can provide units', () => { - let propertiesToTest = [ + const propertiesToTest = [ 'left', 'right', 'top', 'bottom', 'borderWidth' ].forEach((property: string) => { - let testSet: (string | number)[] = [property, 1]; + const testSet: (string | number)[] = [property, 1]; provideUnits(testSet); @@ -20,12 +20,12 @@ describe('provideUnits', () => { }); it('can provide units for directional props', () => { - let propertiesToTest = [ + const propertiesToTest = [ 'padding', 'margin', 'border' ].forEach((property: string) => { - let testSet: (string | number)[] = [ + const testSet: (string | number)[] = [ property, 1, property + 'Left', 1, property + 'Right', 1, diff --git a/packages/merge-styles/src/transforms/provideUnits.ts b/packages/merge-styles/src/transforms/provideUnits.ts index 9374ca550e5bb0..e9f03f85b18748 100644 --- a/packages/merge-styles/src/transforms/provideUnits.ts +++ b/packages/merge-styles/src/transforms/provideUnits.ts @@ -23,7 +23,7 @@ let PX_BASED_PROPERTIES: string[] = [ export function provideUnits(rulePairs: (string | number)[]): void { for (let i = 0; i < rulePairs.length; i += 2) { - let value = rulePairs[i + 1]; + const value = rulePairs[i + 1]; if (typeof value === 'number' && PX_BASED_PROPERTIES.indexOf(rulePairs[i] as string) >= 0) { rulePairs[i + 1] = `${value}px`; } diff --git a/packages/merge-styles/src/transforms/rtlifyRules.test.ts b/packages/merge-styles/src/transforms/rtlifyRules.test.ts index 9c31b6ff071128..3ce13494f28df0 100644 --- a/packages/merge-styles/src/transforms/rtlifyRules.test.ts +++ b/packages/merge-styles/src/transforms/rtlifyRules.test.ts @@ -1,6 +1,6 @@ import { setRTL, rtlifyRules } from './rtlifyRules'; -let { expect } = chai; +const { expect } = chai; describe('rtlifyRules', () => { @@ -41,7 +41,7 @@ describe('rtlifyRules', () => { }); it('does not flip an unflippable cursor', () => { - let rules = ['cursor', 'hand']; + const rules = ['cursor', 'hand']; expect(rtlifyRules(rules)).eqls(['cursor', 'hand']); }); diff --git a/packages/merge-styles/src/transforms/rtlifyRules.ts b/packages/merge-styles/src/transforms/rtlifyRules.ts index 02b556ff17af97..cd1c178f1c8a30 100644 --- a/packages/merge-styles/src/transforms/rtlifyRules.ts +++ b/packages/merge-styles/src/transforms/rtlifyRules.ts @@ -30,8 +30,8 @@ export function getRTL(): boolean { export function rtlifyRules(rulePairs: string[]): string[] { if (getRTL()) { for (let nameIndex = 0, valueIndex = 1; nameIndex < rulePairs.length; nameIndex += 2, valueIndex += 2) { - let name = rulePairs[nameIndex]; - let value = rulePairs[valueIndex]; + const name = rulePairs[nameIndex]; + const value = rulePairs[valueIndex]; if (value.indexOf(NO_FLIP) >= 0) { continue; @@ -65,8 +65,8 @@ export function rtlifyRules(rulePairs: string[]): string[] { } function negateNum(value: string, partIndex: number): string { - let parts = value.split(' '); - let numberVal = parseInt(parts[partIndex], 10); + const parts = value.split(' '); + const numberVal = parseInt(parts[partIndex], 10); parts[0] = parts[0].replace(String(numberVal), String(numberVal * -1)); @@ -75,7 +75,7 @@ function negateNum(value: string, partIndex: number): string { function flipQuad(value: string): string { if (typeof value === 'string') { - let parts = value.split(' '); + const parts = value.split(' '); if (parts.length === 4) { return `${parts[0]} ${parts[3]} ${parts[2]} ${parts[1]}`; From 74b3f41ea0826aff1d0c0c5186fa9438ee215a63 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Thu, 17 Aug 2017 19:15:13 -0700 Subject: [PATCH 09/17] pr feedback. --- .../merge-styles/src/concatStyleSets.test.ts | 6 ++---- packages/merge-styles/src/concatStyleSets.ts | 7 ++++--- packages/merge-styles/src/mergeStyleSets.ts | 2 +- packages/merge-styles/src/styleToClassName.ts | 19 +++++++++---------- 4 files changed, 16 insertions(+), 18 deletions(-) diff --git a/packages/merge-styles/src/concatStyleSets.test.ts b/packages/merge-styles/src/concatStyleSets.test.ts index b94b7e481636e2..4d7e59d8cfe1ed 100644 --- a/packages/merge-styles/src/concatStyleSets.test.ts +++ b/packages/merge-styles/src/concatStyleSets.test.ts @@ -1,12 +1,10 @@ import { concatStyleSets } from './concatStyleSets'; - +import { IStyle } from './IStyle'; const { expect } = chai; describe('concatStyleSets', () => { it('can concat style sets', () => { - - // tslint:disable-next-line:no-any - const result = concatStyleSets( + const result = concatStyleSets<{ root?: IStyle, a?: IStyle, b?: IStyle }>( { root: { background: 'red' }, a: { background: 'green' } diff --git a/packages/merge-styles/src/concatStyleSets.ts b/packages/merge-styles/src/concatStyleSets.ts index 51e79176e3c19f..7ceb0d2cdb2220 100644 --- a/packages/merge-styles/src/concatStyleSets.ts +++ b/packages/merge-styles/src/concatStyleSets.ts @@ -4,8 +4,9 @@ import { IStyleSet } from './IStyleSet'; * Combine a set of styles together (but does not register css classes.) * @public */ -export function concatStyleSets(...args: (T | false | null | undefined)[]): T { - const mergedSet: IStyleSet = {}; +export function concatStyleSets(...args: (T | false | null | undefined)[]): T { + // tslint:disable-next-line:no-any + const mergedSet: T = {} as any; for (const currentSet of args) { if (currentSet) { @@ -27,5 +28,5 @@ export function concatStyleSets(...args: (T | false | null | undef } } - return mergedSet as T; + return mergedSet; } \ No newline at end of file diff --git a/packages/merge-styles/src/mergeStyleSets.ts b/packages/merge-styles/src/mergeStyleSets.ts index 16dbcafff407c0..5ad495f072c048 100644 --- a/packages/merge-styles/src/mergeStyleSets.ts +++ b/packages/merge-styles/src/mergeStyleSets.ts @@ -8,7 +8,7 @@ import { IStyle } from './IStyle'; * * @public */ -export function mergeStyleSets( +export function mergeStyleSets( ...cssSets: T[] ): {[P in keyof T]?: string } { const classNameSet: {[P in keyof T]?: string } = {}; diff --git a/packages/merge-styles/src/styleToClassName.ts b/packages/merge-styles/src/styleToClassName.ts index 45dc4292d76701..382ff972ec65b4 100644 --- a/packages/merge-styles/src/styleToClassName.ts +++ b/packages/merge-styles/src/styleToClassName.ts @@ -19,21 +19,21 @@ function toRuleEntry(name: string, value: string): string | undefined { } // Kebab case the rule. - const rules: string[] = [ + const rulePair: string[] = [ name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(), value ]; - const ruleEntries: string[] = []; - // Apply transforms. - provideUnits(rules); - rtlifyRules(rules); - prefixRules(rules); + provideUnits(rulePair); + rtlifyRules(rulePair); + prefixRules(rulePair); + + const ruleEntries: string[] = []; // Stringify the rules. - for (let i = 0; i < rules.length; i += 2) { - ruleEntries.push(rules[i], ':', rules[i + 1], ';'); + for (let i = 0; i < rulePair.length; i += 2) { + ruleEntries.push(rulePair[i], ':', rulePair[i + 1], ';'); } return ruleEntries.join(''); @@ -125,8 +125,7 @@ function serializeRules(rules: Map): string | undefined { for (const propName in ruleEntries) { if (ruleEntries.hasOwnProperty(propName)) { hasProps = true; - serialized.push(propName); - serialized.push(ruleEntries[propName]); + serialized.push(propName, ruleEntries[propName]); } } }); From ebdcfd59f41e41abcb469c96e98703999e16b03a Mon Sep 17 00:00:00 2001 From: David Zearing Date: Thu, 17 Aug 2017 19:22:10 -0700 Subject: [PATCH 10/17] Assume pixels when providing number types. --- packages/merge-styles/api/merge-styles.api.ts | 4 +-- .../src/transforms/provideUnits.ts | 25 +------------------ 2 files changed, 3 insertions(+), 26 deletions(-) diff --git a/packages/merge-styles/api/merge-styles.api.ts b/packages/merge-styles/api/merge-styles.api.ts index eb0149664bfef2..e6d8ca3dcc21e6 100644 --- a/packages/merge-styles/api/merge-styles.api.ts +++ b/packages/merge-styles/api/merge-styles.api.ts @@ -1,5 +1,5 @@ // @public -export function concatStyleSets < T extends {} >(...args: (T | false | null | undefined)[]): T; +export function concatStyleSets < T extends object >(...args: (T | false | null | undefined)[]): T; // @public export function fontFace(font: IFontFace): void; @@ -333,7 +333,7 @@ export function keyframes(timeline: { [key: string]: {} }): string; export function mergeStyles(...args: (IStyle | IStyle[])[]): string; // @public -export function mergeStyleSets < T extends {} >(...cssSets: T[]): {[P in keyof T]?: string }; +export function mergeStyleSets < T extends object >(...cssSets: T[]): {[P in keyof T]?: string }; // @public class Stylesheet { diff --git a/packages/merge-styles/src/transforms/provideUnits.ts b/packages/merge-styles/src/transforms/provideUnits.ts index e9f03f85b18748..019eacd83d891b 100644 --- a/packages/merge-styles/src/transforms/provideUnits.ts +++ b/packages/merge-styles/src/transforms/provideUnits.ts @@ -1,30 +1,7 @@ -let PX_BASED_PROPERTIES: string[] = [ - 'borderRadius', - 'borderWidth', - 'bottom', - 'left', - 'right', - 'top', -]; - -[ - 'border', - 'margin', - 'padding' -].forEach((prop: string) => { - PX_BASED_PROPERTIES.push( - prop, - prop + 'Left', - prop + 'Right', - prop + 'Top', - prop + 'Bottom' - ); -}); - export function provideUnits(rulePairs: (string | number)[]): void { for (let i = 0; i < rulePairs.length; i += 2) { const value = rulePairs[i + 1]; - if (typeof value === 'number' && PX_BASED_PROPERTIES.indexOf(rulePairs[i] as string) >= 0) { + if (typeof value === 'number') { rulePairs[i + 1] = `${value}px`; } } From 12b357879263ca49949ec80d70fc5e3970b8c3c3 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Thu, 17 Aug 2017 19:26:41 -0700 Subject: [PATCH 11/17] ignore opacity. --- .../merge-styles/src/transforms/provideUnits.test.ts | 11 +++++++++++ packages/merge-styles/src/transforms/provideUnits.ts | 6 +++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/merge-styles/src/transforms/provideUnits.test.ts b/packages/merge-styles/src/transforms/provideUnits.test.ts index 1aef330b9d0e38..e2eb3e11f6978a 100644 --- a/packages/merge-styles/src/transforms/provideUnits.test.ts +++ b/packages/merge-styles/src/transforms/provideUnits.test.ts @@ -43,6 +43,17 @@ describe('provideUnits', () => { property + 'Bottom', '1px' ]); }); + }); + + it('ignores opacity', () => { + const testSet = [ + 'opacity', + 0 + ]; + provideUnits(testSet); + + expect(testSet).eql(['opacity', 0]); }); + }); \ No newline at end of file diff --git a/packages/merge-styles/src/transforms/provideUnits.ts b/packages/merge-styles/src/transforms/provideUnits.ts index 019eacd83d891b..cd538438f78639 100644 --- a/packages/merge-styles/src/transforms/provideUnits.ts +++ b/packages/merge-styles/src/transforms/provideUnits.ts @@ -1,7 +1,11 @@ export function provideUnits(rulePairs: (string | number)[]): void { for (let i = 0; i < rulePairs.length; i += 2) { + const name = rulePairs[i]; const value = rulePairs[i + 1]; - if (typeof value === 'number') { + if ( + name !== 'opacity' && + typeof value === 'number' + ) { rulePairs[i + 1] = `${value}px`; } } From 603e1f184060085cdbff915fe1879946ac38bd38 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Thu, 17 Aug 2017 19:33:03 -0700 Subject: [PATCH 12/17] Adding keyframes test. --- packages/merge-styles/src/keyframes.test.ts | 50 +++++++++++++++++++++ packages/merge-styles/src/keyframes.ts | 2 +- 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 packages/merge-styles/src/keyframes.test.ts diff --git a/packages/merge-styles/src/keyframes.test.ts b/packages/merge-styles/src/keyframes.test.ts new file mode 100644 index 00000000000000..573a4fb8d3379c --- /dev/null +++ b/packages/merge-styles/src/keyframes.test.ts @@ -0,0 +1,50 @@ +import { keyframes } from './keyframes'; +import { + Stylesheet, + InjectionMode +} from './Stylesheet'; + +const { expect } = chai; +const _stylesheet: Stylesheet = Stylesheet.getInstance(); + +_stylesheet.setConfig({ injectionMode: InjectionMode.none }); + +describe('keyframes', () => { + beforeEach(() => { + _stylesheet.reset(); + }); + + it('can register from/to keyframes', () => { + keyframes({ + from: { + opacity: 0, + }, + to: { + opacity: 1 + } + }); + + expect(_stylesheet.getRules()).equals( + '@keyframes css-0{from{opacity:0;}to{opacity:1;}}' + ); + }); + + it('can register percentage keyframes', () => { + keyframes({ + '0%': { + opacity: 0, + }, + '50%': { + opacity: .8 + }, + '100%': { + opacity: 1 + } + }); + + expect(_stylesheet.getRules()).equals( + '@keyframes css-0{0%{opacity:0;}50%{opacity:0.8;}100%{opacity:1;}}' + ); + }); + +}); \ No newline at end of file diff --git a/packages/merge-styles/src/keyframes.ts b/packages/merge-styles/src/keyframes.ts index e0ab28ec5c02fb..fec40daa0e921e 100644 --- a/packages/merge-styles/src/keyframes.ts +++ b/packages/merge-styles/src/keyframes.ts @@ -14,7 +14,7 @@ export function keyframes(timeline: { [key: string]: {} }): string { for (const prop in timeline) { if (timeline.hasOwnProperty(prop)) { - rulesArray.push(prop, ' {', serializeRuleEntries(timeline[prop]), '}'); + rulesArray.push(prop, '{', serializeRuleEntries(timeline[prop]), '}'); } } const rules = rulesArray.join(''); From 11e1a50198e772cf68f7062f1a4263d7df169d32 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Thu, 17 Aug 2017 20:00:22 -0700 Subject: [PATCH 13/17] Adding comments, removing obsolete or deprecated properties from rawstyle interface. --- packages/merge-styles/README.md | 4 +- packages/merge-styles/api/merge-styles.api.ts | 90 ++------ packages/merge-styles/src/IRawStyle.ts | 196 ++---------------- packages/merge-styles/src/IStyle.ts | 7 + packages/merge-styles/src/Stylesheet.ts | 62 +++++- packages/merge-styles/src/index.ts | 6 + packages/merge-styles/tslint.json | 4 +- 7 files changed, 112 insertions(+), 257 deletions(-) diff --git a/packages/merge-styles/README.md b/packages/merge-styles/README.md index cc59a13bc8d442..2c98653b9628a2 100644 --- a/packages/merge-styles/README.md +++ b/packages/merge-styles/README.md @@ -1,6 +1,6 @@ -# [Office UI Fabric - merge-styles](http://dev.office.com/fabric) +# [merge-styles](http://dev.office.com/fabric) -The merge-styles library provides a number of utilities for loading styles through javascript. It is designed to make it simple to style components through javascript. It generates css rules, rather than using inline styling, to ensure we can use css features like pseudo selectors (:hover) and parent/child selectors (media queries). +The `merge-styles` library provides a number of utilities for loading styles through javascript. It is designed to make it simple to style components through javascript. It generates css rules, rather than using inline styling, to ensure we can use css features like pseudo selectors (:hover) and parent/child selectors (media queries). The library was built for speed and size; the entire package is 2.7k gzipped. diff --git a/packages/merge-styles/api/merge-styles.api.ts b/packages/merge-styles/api/merge-styles.api.ts index e6d8ca3dcc21e6..9c43cf64f83291 100644 --- a/packages/merge-styles/api/merge-styles.api.ts +++ b/packages/merge-styles/api/merge-styles.api.ts @@ -6,34 +6,35 @@ export function fontFace(font: IFontFace): void; // @public interface IExtendedRawStyle extends IRawStyle { - // (undocumented) displayName?: string; - // (undocumented) selectors?: { [ key: string ]: IStyle; } } -// @public (undocumented) +// @public interface IFontFace extends IRawFontStyle { - // (undocumented) fontFeatureSettings?: string; src?: string; unicodeRange?: ICSSRule | string; } -// @public (undocumented) +// @public +enum InjectionMode { + insertNode = 1, + none = 0 +} + +// @public interface IRawStyle extends IRawFontStyle { alignContent?: ICSSRule | 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around' | 'stretch'; alignItems?: ICSSRule | 'flex-start' | 'flex-end' | 'center' | 'baseline' | 'stretch'; alignmentAdjust?: ICSSRule | string; - // (undocumented) alignmentBaseline?: ICSSRule | string; alignSelf?: ICSSRule | 'auto' | 'flex-start' | 'flex-end' | 'center' | 'baseline' | 'stretch'; animationDelay?: ICSSRule | string; animationDirection?: ICSSRule | string; animationDuration?: ICSSRule | string; - // (undocumented) animationFillMode?: ICSSRule | 'none' | 'forwards' | 'backwards' | 'both'; animationIterationCount?: ICSSRule | string; animationName?: ICSSRule | string; @@ -45,14 +46,11 @@ interface IRawStyle extends IRawFontStyle { backgroundAttachment?: ICSSRule | 'scroll' | 'fixed' | 'local'; backgroundBlendMode?: ICSSRule | string; backgroundColor?: ICSSRule | string; - // (undocumented) backgroundComposite?: ICSSRule | string; backgroundImage?: ICSSRule | string; backgroundOrigin?: ICSSRule | string; backgroundPosition?: ICSSRule | string; backgroundRepeat?: ICSSRule | string; - baselineShift?: ICSSRule | string; - behavior?: ICSSRule | string; border?: ICSSRule | 0 | string; borderBottom?: ICSSRule | number | string; borderBottomColor?: ICSSRule | string; @@ -84,23 +82,13 @@ interface IRawStyle extends IRawFontStyle { borderTopWidth?: ICSSRule | string; borderWidth?: ICSSRule | number | string; bottom?: ICSSRule | number | string; - // (undocumented) - boxAlign?: ICSSRule | string; boxDecorationBreak?: ICSSRule | string; - // (undocumented) - boxDirection?: ICSSRule | string; - boxFlex?: ICSSRule | number; - boxFlexGroup?: ICSSRule | number; - boxLineProgression?: ICSSRule | string; - boxLines?: ICSSRule | string; - boxOrdinalGroup?: ICSSRule | string; boxShadow?: ICSSRule | string; boxSizing?: ICSSRule | 'border-box' | 'content-box'; breakAfter?: ICSSRule | string; breakBefore?: ICSSRule | string; breakInside?: ICSSRule | string; clear?: ICSSRule | string; - clip?: ICSSRule | string; clipRule?: ICSSRule | string; color?: ICSSRule | string; columnCount?: ICSSRule | number | 'auto'; @@ -125,13 +113,10 @@ interface IRawStyle extends IRawFontStyle { fillRule?: ICSSRule | string; filter?: ICSSRule | string; flex?: ICSSRule | number | string; - flexAlign?: ICSSRule | string; flexBasis?: ICSSRule | string; flexDirection?: ICSSRule | 'row' | 'row-reverse' | 'column' | 'column-reverse'; flexFlow?: ICSSRule | string; flexGrow?: ICSSRule | number; - flexItemAlign?: ICSSRule | string; - flexLinePack?: ICSSRule | string; flexOrder?: ICSSRule | string; flexShrink?: ICSSRule | number; flexWrap?: ICSSRule | 'nowrap' | 'wrap' | 'wrap-reverse'; @@ -144,8 +129,6 @@ interface IRawStyle extends IRawFontStyle { gridRow?: ICSSRule | string; gridRowEnd?: ICSSRule | string; gridRowPosition?: ICSSRule | string; - // (undocumented) - gridRowSpan?: ICSSRule | string; gridTemplateAreas?: ICSSRule | string; gridTemplateColumns?: ICSSRule | string; gridTemplateRows?: ICSSRule | string; @@ -154,24 +137,9 @@ interface IRawStyle extends IRawFontStyle { hyphenateLimitLines?: ICSSRule | string; hyphenateLimitZone?: ICSSRule | string; hyphens?: ICSSRule | string; - // (undocumented) - imeMode?: ICSSRule | string; justifyContent?: ICSSRule | 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around' | 'space-evenly'; - // (undocumented) - layoutGrid?: ICSSRule | string; - // (undocumented) - layoutGridChar?: ICSSRule | string; - // (undocumented) - layoutGridLine?: ICSSRule | string; - // (undocumented) - layoutGridMode?: ICSSRule | string; - // (undocumented) - layoutGridType?: ICSSRule | string; left?: ICSSRule | number | string; letterSpacing?: ICSSRule | string; - lineBreak?: ICSSRule | string; - // (undocumented) - lineClamp?: ICSSRule | number; lineHeight?: ICSSRule | 'normal' | number | ICSSLengthRule | ICSSPercentageRule; listStyle?: ICSSRule | string; listStyleImage?: ICSSRule | string; @@ -224,16 +192,11 @@ interface IRawStyle extends IRawFontStyle { perspectiveOrigin?: ICSSRule | string; pointerEvents?: ICSSRule | string; position?: ICSSRule | 'static' | 'relative' | 'absolute' | 'fixed' | 'sticky'; - punctuationTrim?: ICSSRule | string; quotes?: ICSSRule | string; regionFragment?: ICSSRule | string; restAfter?: ICSSRule | string; restBefore?: ICSSRule | string; right?: ICSSRule | number | string; - // (undocumented) - rubyAlign?: ICSSRule | string; - // (undocumented) - rubyPosition?: ICSSRule | string; shapeImageThreshold?: ICSSRule | string; shapeInside?: ICSSRule | string; shapeMargin?: ICSSRule | string; @@ -249,30 +212,13 @@ interface IRawStyle extends IRawFontStyle { textDecoration?: ICSSRule | string; textDecorationColor?: ICSSRule | string; textDecorationLine?: ICSSRule | string; - // (undocumented) - textDecorationLineThrough?: ICSSRule | string; - // (undocumented) - textDecorationNone?: ICSSRule | string; - // (undocumented) - textDecorationOverline?: ICSSRule | string; textDecorationSkip?: ICSSRule | string; textDecorationStyle?: ICSSRule | string; - // (undocumented) - textDecorationUnderline?: ICSSRule | string; textEmphasis?: ICSSRule | string; textEmphasisColor?: ICSSRule | string; textEmphasisStyle?: ICSSRule | string; textHeight?: ICSSRule | string; textIndent?: ICSSRule | string; - // (undocumented) - textJustifyTrim?: ICSSRule | string; - // (undocumented) - textKashidaSpace?: ICSSRule | string; - textLineThrough?: ICSSRule | string; - textLineThroughColor?: ICSSRule | string; - textLineThroughMode?: ICSSRule | string; - textLineThroughStyle?: ICSSRule | string; - textLineThroughWidth?: ICSSRule | string; textOverflow?: ICSSRule | string; textOverline?: ICSSRule | string; textOverlineColor?: ICSSRule | string; @@ -280,7 +226,6 @@ interface IRawStyle extends IRawFontStyle { textOverlineStyle?: ICSSRule | string; textOverlineWidth?: ICSSRule | string; textRendering?: ICSSRule | string; - textScript?: ICSSRule | string; textShadow?: ICSSRule | string; textTransform?: ICSSRule | string; textUnderlinePosition?: ICSSRule | string; @@ -312,7 +257,6 @@ interface IRawStyle extends IRawFontStyle { voiceVolume?: ICSSRule | string; WebkitFontSmoothing?: 'none' | 'antialiased' | 'grayscale' | 'subpixel-antialiased'; whiteSpace?: ICSSRule | string; - whiteSpaceTreatment?: ICSSRule | string; widows?: ICSSRule | number; width?: ICSSRule | string; wordBreak?: ICSSRule | string; @@ -320,12 +264,16 @@ interface IRawStyle extends IRawFontStyle { wordWrap?: ICSSRule | string; wrapFlow?: ICSSRule | string; wrapMargin?: ICSSRule | string; - wrapOption?: ICSSRule | string; writingMode?: ICSSRule | string; zIndex?: ICSSRule | 'auto' | number; zoom?: ICSSRule | 'auto' | number | ICSSPercentageRule; } +// @public +interface IStyleSheetConfig { + injectionMode?: InjectionMode; +} + // @public export function keyframes(timeline: { [key: string]: {} }): string; @@ -337,29 +285,19 @@ export function mergeStyleSets < T extends object >(...cssSets: T[]): {[P in key // @public class Stylesheet { - // WARNING: The type "IStyleSheetConfig" needs to be exported by the package (e.g. added to index.ts) constructor(config?: IStyleSheetConfig); - // (undocumented) public argsFromClassName(className: string): IStyle[] | undefined; - // (undocumented) public cacheClassName(className: string, key: string, args: IStyle[]): void; - // (undocumented) public classNameFromKey(key: string): string | undefined; - // (undocumented) public getClassName(displayName?: string): string; - // (undocumented) public static getInstance(): Stylesheet; - // (undocumented) public getRules(): string; - // (undocumented) public insertRule(rule: string): void; - // (undocumented) public reset(): void; - // WARNING: The type "IStyleSheetConfig" needs to be exported by the package (e.g. added to index.ts) - // (undocumented) public setConfig(config?: IStyleSheetConfig): void; } // WARNING: Unsupported export: IStyle +// WARNING: Unsupported export: IStyleSet // WARNING: Unsupported export: IFontWeight // (No packageDescription for this package) diff --git a/packages/merge-styles/src/IRawStyle.ts b/packages/merge-styles/src/IRawStyle.ts index 8e88369ba63574..14cc09f493a18c 100644 --- a/packages/merge-styles/src/IRawStyle.ts +++ b/packages/merge-styles/src/IRawStyle.ts @@ -11,6 +11,9 @@ export type ICSSLengthRule = number | string; export type IFontWeight = ICSSRule | 'normal' | 'bold' | 'bolder' | 'lighter' | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; +/** + * The base font style. + */ export interface IRawFontStyle { /** * The font property is shorthand that allows you to do one of two things: you can @@ -115,6 +118,8 @@ export interface IRawFontStyle { } /** + * Font face definition. + * * @public */ export interface IFontFace extends IRawFontStyle { @@ -130,10 +135,15 @@ export interface IFontFace extends IRawFontStyle { */ unicodeRange?: ICSSRule | string; + /** + * Feature settings for the font. + */ fontFeatureSettings?: string; } /** + * All raw style properties. + * * @public */ export interface IRawStyle extends IRawFontStyle { @@ -173,6 +183,13 @@ export interface IRawStyle extends IRawFontStyle { */ alignmentAdjust?: ICSSRule | string; + /** + * Specifies how an object is aligned with respect to its parent. This property specifies + * which baseline of this element is to be aligned with the corresponding baseline of the + * parent. For example, this allows alphabetic baselines in Roman text to stay aligned + * across font size changes. It defaults to the baseline with the same name as the computed + * value of the alignment-baseline property. + */ alignmentBaseline?: ICSSRule | string; /** @@ -192,7 +209,8 @@ export interface IRawStyle extends IRawFontStyle { animationDuration?: ICSSRule | string; /** - * + * The animation-fill-mode CSS property specifies how a CSS animation should apply + * styles to its target before and after its execution. */ animationFillMode?: ICSSRule | 'none' | 'forwards' | 'backwards' | 'both'; @@ -259,6 +277,9 @@ export interface IRawStyle extends IRawFontStyle { */ backgroundColor?: ICSSRule | string; + /** + * Sets a compositing style for background images and colors. + */ backgroundComposite?: ICSSRule | string; /** @@ -283,16 +304,6 @@ export interface IRawStyle extends IRawFontStyle { */ backgroundRepeat?: ICSSRule | string; - /** - * Obsolete - spec retired, not implemented. - */ - baselineShift?: ICSSRule | string; - - /** - * Non standard. Sets or retrieves the location of the Dynamic HTML (DHTML) behavior. - */ - behavior?: ICSSRule | string; - /** * Shorthand property that defines the different properties of all four sides of an * element's border in a single declaration. It can be used to set border-width, @@ -511,11 +522,6 @@ export interface IRawStyle extends IRawFontStyle { */ bottom?: ICSSRule | number | string; - /** - * Obsolete. - */ - boxAlign?: ICSSRule | string; - /** * Breaks a box into fragments creating new borders, padding and repeating backgrounds * or lets it stay as a continuous box on a page break, column break, or, for inline @@ -523,43 +529,6 @@ export interface IRawStyle extends IRawFontStyle { */ boxDecorationBreak?: ICSSRule | string; - /** - * Deprecated - */ - boxDirection?: ICSSRule | string; - - /** - * Do not use. This property has been replaced by the flex-wrap property. - * Gets or sets a value that specifies the direction to add successive rows or columns - * when the value of box-lines is set to multiple. - */ - boxLineProgression?: ICSSRule | string; - - /** - * Do not use. This property has been replaced by the flex-wrap property. - * Gets or sets a value that specifies whether child elements wrap onto multiple lines - * or columns based on the space available in the object. - */ - boxLines?: ICSSRule | string; - - /** - * Do not use. This property has been replaced by flex-order. - * Specifies the ordinal group that a child element of the object belongs to. This - * ordinal value identifies the display order (along the axis defined by the box-orient - * property) for the group. - */ - boxOrdinalGroup?: ICSSRule | string; - - /** - * Deprecated. - */ - boxFlex?: ICSSRule | number; - - /** - * Deprecated. - */ - boxFlexGroup?: ICSSRule | number; - /** * Cast a drop shadow from the frame of almost any element. * MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow @@ -597,13 +566,6 @@ export interface IRawStyle extends IRawFontStyle { */ clear?: ICSSRule | string; - /** - * Deprecated; see clip-path. - * Lets you specify the dimensions of an absolutely positioned element that should be - * visible, and the element is clipped into this shape, and displayed. - */ - clip?: ICSSRule | string; - /** * Clipping crops an graphic, so that only a portion of the graphic is rendered, or * filled. This clip-rule property, when used with the clip-path property, defines @@ -760,13 +722,6 @@ export interface IRawStyle extends IRawFontStyle { */ flex?: ICSSRule | number | string; - /** - * Obsolete, do not use. This property has been renamed to align-items. - * Specifies the alignment (perpendicular to the layout axis defined by the - * flex-direction property) of child elements of the object. - */ - flexAlign?: ICSSRule | string; - /** * The flex-basis CSS property describes the initial main size of the flex item before * any free space is distributed according to the flex factors described in the flex @@ -792,20 +747,6 @@ export interface IRawStyle extends IRawFontStyle { */ flexGrow?: ICSSRule | number; - /** - * Do not use. This property has been renamed to align-self - * Specifies the alignment (perpendicular to the layout axis defined by flex-direction) of child elements of the object. - */ - flexItemAlign?: ICSSRule | string; - - /** - * Do not use. This property has been renamed to align-content. - * Specifies how a flexbox's lines align within the flexbox when there is extra space - * along the axis that is perpendicular to the axis defined by the flex-direction - * property. - */ - flexLinePack?: ICSSRule | string; - /** * Gets or sets a value that specifies the ordinal group that a flexbox element * belongs to. This ordinal value identifies the display order for the group. @@ -895,8 +836,6 @@ export interface IRawStyle extends IRawFontStyle { */ gridRowPosition?: ICSSRule | string; - gridRowSpan?: ICSSRule | string; - /** * Specifies named grid areas which are not associated with any particular grid item, * but can be referenced from the grid-placement properties. The syntax of the @@ -951,8 +890,6 @@ export interface IRawStyle extends IRawFontStyle { */ hyphens?: ICSSRule | string; - imeMode?: ICSSRule | string; - /** * Defines how the browser distributes space between and around flex items * along the main-axis of their container. @@ -961,16 +898,6 @@ export interface IRawStyle extends IRawFontStyle { */ justifyContent?: ICSSRule | 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around' | 'space-evenly'; - layoutGrid?: ICSSRule | string; - - layoutGridChar?: ICSSRule | string; - - layoutGridLine?: ICSSRule | string; - - layoutGridMode?: ICSSRule | string; - - layoutGridType?: ICSSRule | string; - /** * Sets the left position of an element relative to the nearest anscestor that is set * to position absolute, relative, or fixed. @@ -983,14 +910,6 @@ export interface IRawStyle extends IRawFontStyle { */ letterSpacing?: ICSSRule | string; - /** - * Deprecated. Gets or sets line-breaking rules for text in selected languages such as - * Japanese, Chinese, and Korean. - */ - lineBreak?: ICSSRule | string; - - lineClamp?: ICSSRule | number; - /** * Specifies the height of an inline block level element. * See CSS 2.1 line-height property https://www.w3.org/TR/CSS21/visudet.html#propdef-line-height @@ -1357,14 +1276,6 @@ export interface IRawStyle extends IRawFontStyle { */ position?: ICSSRule | 'static' | 'relative' | 'absolute' | 'fixed' | 'sticky'; - /** - * Obsolete: unsupported. - * This property determines whether or not a full-width punctuation mark character - * should be trimmed if it appears at the beginning of a line, so that its "ink" lines - * up with the first glyph in the line above and below. - */ - punctuationTrim?: ICSSRule | string; - /** * Sets the type of quotation marks for embedded quotations. */ @@ -1399,10 +1310,6 @@ export interface IRawStyle extends IRawFontStyle { */ right?: ICSSRule | number | string; - rubyAlign?: ICSSRule | string; - - rubyPosition?: ICSSRule | string; - /** * Defines the alpha channel threshold used to extract a shape from an image. Can be * thought of as a "minimum opacity" threshold; that is, a value of 0.5 means that the @@ -1502,12 +1409,6 @@ export interface IRawStyle extends IRawFontStyle { */ textDecorationLine?: ICSSRule | string; - textDecorationLineThrough?: ICSSRule | string; - - textDecorationNone?: ICSSRule | string; - - textDecorationOverline?: ICSSRule | string; - /** * Specifies what parts of an element’s content are skipped over when applying any * text decoration. @@ -1521,8 +1422,6 @@ export interface IRawStyle extends IRawFontStyle { */ textDecorationStyle?: ICSSRule | string; - textDecorationUnderline?: ICSSRule | string; - /** * The text-emphasis property will apply special emphasis marks to the elements text. * Slightly similar to the text-decoration property only that this property can have @@ -1559,41 +1458,6 @@ export interface IRawStyle extends IRawFontStyle { */ textIndent?: ICSSRule | string; - textJustifyTrim?: ICSSRule | string; - - textKashidaSpace?: ICSSRule | string; - - /** - * The text-line-through property is a shorthand property for text-line-through-style, - * text-line-through-color and text-line-through-mode. (Considered obsolete; use - * text-decoration instead.) - */ - textLineThrough?: ICSSRule | string; - - /** - * Specifies the line colors for the line-through text decoration. - * (Considered obsolete; use text-decoration-color instead.) - */ - textLineThroughColor?: ICSSRule | string; - - /** - * Sets the mode for the line-through text decoration, determining whether the text - * decoration affects the space characters or not. (Considered obsolete; use - * text-decoration-skip instead.) - */ - textLineThroughMode?: ICSSRule | string; - - /** - * Specifies the line style for line-through text decoration. - * (Considered obsolete; use text-decoration-style instead.) - */ - textLineThroughStyle?: ICSSRule | string; - - /** - * Specifies the line width for the line-through text decoration. - */ - textLineThroughWidth?: ICSSRule | string; - /** * The text-overflow shorthand CSS property determines how overflowed content that is * not displayed is signaled to the users. It can be clipped, display an ellipsis @@ -1635,11 +1499,6 @@ export interface IRawStyle extends IRawFontStyle { */ textRendering?: ICSSRule | string; - /** - * Obsolete: unsupported. - */ - textScript?: ICSSRule | string; - /** * The CSS text-shadow property applies one or more drop shadows to the text and * of an element. Each shadow is specified as an offset from the @@ -1837,11 +1696,6 @@ export interface IRawStyle extends IRawFontStyle { */ whiteSpace?: ICSSRule | string; - /** - * Obsolete: unsupported. - */ - whiteSpaceTreatment?: ICSSRule | string; - /** * In paged media, this property defines the mimimum number of lines that must be left * at the top of the second page. @@ -1889,12 +1743,6 @@ export interface IRawStyle extends IRawFontStyle { */ wrapMargin?: ICSSRule | string; - /** - * Obsolete and unsupported. Do not use. - * This CSS property controls the text when it reaches the end of the block in which it is enclosed. - */ - wrapOption?: ICSSRule | string; - /** * writing-mode specifies if lines of text are laid out horizontally or vertically, * and the direction which lines of text and blocks progress. diff --git a/packages/merge-styles/src/IStyle.ts b/packages/merge-styles/src/IStyle.ts index 9ee5db22535385..4a46df0baaf590 100644 --- a/packages/merge-styles/src/IStyle.ts +++ b/packages/merge-styles/src/IStyle.ts @@ -6,7 +6,14 @@ import { IRawStyle } from './IRawStyle'; * @public */ export interface IExtendedRawStyle extends IRawStyle { + /** + * Display name for the style. + */ displayName?: string; + + /** + * Custom selectors for the style. + */ selectors?: { [key: string]: IStyle; }; diff --git a/packages/merge-styles/src/Stylesheet.ts b/packages/merge-styles/src/Stylesheet.ts index 20cbe249c1e313..257954b4f157af 100644 --- a/packages/merge-styles/src/Stylesheet.ts +++ b/packages/merge-styles/src/Stylesheet.ts @@ -1,11 +1,31 @@ import { IStyle } from './IStyle'; +/** + * Injection mode for the stylesheet. + * + * @public + */ export const enum InjectionMode { + /** + * Avoids style injection, use getRules() to read the styles. + */ none = 0, + + /** + * Inserts rules using the insertRule api. + */ insertNode = 1 } +/** + * Stylesheet config. + * + * @public + */ export interface IStyleSheetConfig { + /** + * Injection mode for how rules are inserted. + */ injectionMode?: InjectionMode; } @@ -32,6 +52,9 @@ export class Stylesheet { // tslint:disable-next-line:no-any private _classNameToArgs: { [key: string]: any }; + /** + * Gets the singleton instance. + */ public static getInstance(): Stylesheet { // tslint:disable-next-line:no-any const win: any = typeof window !== 'undefined' ? window : {}; @@ -54,6 +77,9 @@ export class Stylesheet { this.reset(); } + /** + * Configures the stylesheet. + */ public setConfig(config?: IStyleSheetConfig): void { this._config = { ...this._config, @@ -61,25 +87,45 @@ export class Stylesheet { }; } + /** + * Generates a unique classname. + * + * @param displayName - Optional value to use as a prefix. + */ public getClassName(displayName?: string): string { const prefix = displayName || 'css'; return `${prefix}-${this._counter++}`; } - public classNameFromKey(key: string): string | undefined { - return this._keyToClassName[key]; - } - + /** + * Used internally to cache information about a class which was + * registered with the stylesheet. + */ public cacheClassName(className: string, key: string, args: IStyle[]): void { this._keyToClassName[key] = className; this._classNameToArgs[className] = args; } + /** + * Gets the appropriate classname given a key which was previously + * registered using cacheClassName. + */ + public classNameFromKey(key: string): string | undefined { + return this._keyToClassName[key]; + } + + /** + * Gets the arguments associated with a given classname which was + * previously registered using cacheClassName. + */ public argsFromClassName(className: string): IStyle[] | undefined { return this._classNameToArgs[className]; } + /** + * Inserts a css rule into the stylesheet. + */ public insertRule( rule: string ): void { @@ -104,10 +150,18 @@ export class Stylesheet { } } + /** + * Gets all rules registered with the stylesheet; only valid when + * using InsertionMode.none. + */ public getRules(): string { return (this._rules.join('') || '') + (this._rulesToInsert.join('') || ''); } + /** + * Resets the internal state of the stylesheet. Only used in server + * rendered scenarios where we're using InsertionMode.none. + */ public reset(): void { this._rules = []; this._rulesToInsert = []; diff --git a/packages/merge-styles/src/index.ts b/packages/merge-styles/src/index.ts index 62fb2a0c467c01..785f94b3ab876b 100644 --- a/packages/merge-styles/src/index.ts +++ b/packages/merge-styles/src/index.ts @@ -3,6 +3,10 @@ export { IStyle } from './IStyle'; +export { + IStyleSet +} from './IStyleSet'; + export { IRawStyle, IFontFace, @@ -30,5 +34,7 @@ export { } from './keyframes'; export { + IStyleSheetConfig, + InjectionMode, Stylesheet } from './Stylesheet'; diff --git a/packages/merge-styles/tslint.json b/packages/merge-styles/tslint.json index 621ee6ba046052..009d06e3cf4477 100644 --- a/packages/merge-styles/tslint.json +++ b/packages/merge-styles/tslint.json @@ -2,5 +2,7 @@ "extends": [ "office-ui-fabric-react-tslint" ], - "rules": {} + "rules": { + "prefer-const": true + } } \ No newline at end of file From eeb13a06686a8a94eebb7eb6b50c7e94dc8337c0 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Thu, 17 Aug 2017 20:01:25 -0700 Subject: [PATCH 14/17] Removing import. --- packages/merge-styles/src/styleToClassName.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/merge-styles/src/styleToClassName.ts b/packages/merge-styles/src/styleToClassName.ts index 382ff972ec65b4..1b93a97cad9985 100644 --- a/packages/merge-styles/src/styleToClassName.ts +++ b/packages/merge-styles/src/styleToClassName.ts @@ -1,4 +1,3 @@ -import { GlobalSettings } from '@uifabric/utilities/lib/GlobalSettings'; import { rtlifyRules } from './transforms/rtlifyRules'; import { provideUnits } from './transforms/provideUnits'; import { prefixRules } from './transforms/prefixRules'; From 87d2ca862d130e26c63389ba74dcca034ff76141 Mon Sep 17 00:00:00 2001 From: David Zearing Date: Fri, 18 Aug 2017 12:26:01 -0700 Subject: [PATCH 15/17] Updating to optimize the transforms to an O(n) approach. --- packages/merge-styles/README.md | 2 +- packages/merge-styles/package.json | 3 + packages/merge-styles/src/styleToClassName.ts | 65 +++++++------------ .../src/transforms/kebabRules.test.ts | 34 ++++++++++ .../merge-styles/src/transforms/kebabRules.ts | 6 ++ .../src/transforms/prefixRules.test.ts | 8 +-- .../src/transforms/prefixRules.ts | 12 ++-- .../src/transforms/provideUnits.test.ts | 10 ++- .../src/transforms/provideUnits.ts | 22 ++++--- .../src/transforms/rtlifyRules.test.ts | 21 +++--- .../src/transforms/rtlifyRules.ts | 59 +++++++++-------- packages/merge-styles/tsconfig.json | 2 +- packages/merge-styles/webpack.config.js | 8 +-- 13 files changed, 146 insertions(+), 106 deletions(-) create mode 100644 packages/merge-styles/src/transforms/kebabRules.test.ts create mode 100644 packages/merge-styles/src/transforms/kebabRules.ts diff --git a/packages/merge-styles/README.md b/packages/merge-styles/README.md index 2c98653b9628a2..ed3c6dfaf0e5d5 100644 --- a/packages/merge-styles/README.md +++ b/packages/merge-styles/README.md @@ -2,7 +2,7 @@ The `merge-styles` library provides a number of utilities for loading styles through javascript. It is designed to make it simple to style components through javascript. It generates css rules, rather than using inline styling, to ensure we can use css features like pseudo selectors (:hover) and parent/child selectors (media queries). -The library was built for speed and size; the entire package is 2.7k gzipped. +The library was built for speed and size; the entire package is 2.62k gzipped. It has no dependencies. The basic idea is to provide a method which can take in one or more style objects css styling javascript objects representing the styles for a given element, and return a single class name. If the same set of styling is passed in, the same name returns and nothing is re-registered. diff --git a/packages/merge-styles/package.json b/packages/merge-styles/package.json index 64db12826fb3f7..5b413e8ab5c924 100644 --- a/packages/merge-styles/package.json +++ b/packages/merge-styles/package.json @@ -42,5 +42,8 @@ "source-map-loader": "^0.2.1", "typescript": "2.4.2", "webpack-bundle-analyzer": "^2.2.1" + }, + "dependencies": { + "tslib": "^1.7.1" } } \ No newline at end of file diff --git a/packages/merge-styles/src/styleToClassName.ts b/packages/merge-styles/src/styleToClassName.ts index 1b93a97cad9985..77c72f2d29464c 100644 --- a/packages/merge-styles/src/styleToClassName.ts +++ b/packages/merge-styles/src/styleToClassName.ts @@ -1,43 +1,13 @@ import { rtlifyRules } from './transforms/rtlifyRules'; import { provideUnits } from './transforms/provideUnits'; import { prefixRules } from './transforms/prefixRules'; +import { kebabRules } from './transforms/kebabRules'; import { getVendorSettings } from './getVendorSettings'; import { Stylesheet } from './Stylesheet'; import { IStyle, IExtendedRawStyle } from './IStyle'; const DISPLAY_NAME = 'displayName'; -function toRuleEntry(name: string, value: string): string | undefined { - if (name === DISPLAY_NAME) { - return undefined; - } - - // Prefixes like WebKit need a dash infront of them. - if (/[A-Z]/.test(name[0])) { - name = '-' + name; - } - - // Kebab case the rule. - const rulePair: string[] = [ - name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(), - value - ]; - - // Apply transforms. - provideUnits(rulePair); - rtlifyRules(rulePair); - prefixRules(rulePair); - - const ruleEntries: string[] = []; - - // Stringify the rules. - for (let i = 0; i < rulePair.length; i += 2) { - ruleEntries.push(rulePair[i], ':', rulePair[i + 1], ';'); - } - - return ruleEntries.join(''); -} - function getDisplayName(rules?: Map): string | undefined { const rootStyle: IStyle = rules && rules.get('&'); @@ -114,7 +84,7 @@ function expandQuads( currentRules[name + 'Left'] = parts[3] || parts[1] || parts[0]; } -function serializeRules(rules: Map): string | undefined { +function getKeyForRules(rules: Map): string | undefined { const serialized: string[] = []; let hasProps = false; @@ -132,23 +102,38 @@ function serializeRules(rules: Map): string | undefined { return hasProps ? serialized.join('') : undefined; } -export function serializeRuleEntries(ruleEntries: { [key: string]: string }): string { - const allEntries: string[] = []; +export function serializeRuleEntries(ruleEntries: { [key: string]: string | number }): string { + if (!ruleEntries) { + return ''; + } - if (ruleEntries) { - for (const entry in ruleEntries) { - if (ruleEntries.hasOwnProperty(entry)) { - allEntries.push(toRuleEntry(entry, ruleEntries[entry])!); - } + const allEntries: (string | number)[] = []; + + for (const entry in ruleEntries) { + if (ruleEntries.hasOwnProperty(entry) && entry !== DISPLAY_NAME) { + allEntries.push(entry, ruleEntries[entry]); } } + // Apply transforms. + for (let i = 0; i < allEntries.length; i += 2) { + kebabRules(allEntries, i); + provideUnits(allEntries, i); + rtlifyRules(allEntries, i); + prefixRules(allEntries, i); + } + + // Apply punctuation. + for (let i = 1; i < allEntries.length; i += 4) { + allEntries.splice(i, 1, ':', allEntries[i], ';'); + } + return allEntries.join(''); } export function styleToClassName(...args: IStyle[]): string { const rules: Map = extractRules(args); - const key = serializeRules(rules); + const key = getKeyForRules(rules); let className = ''; if (key) { diff --git a/packages/merge-styles/src/transforms/kebabRules.test.ts b/packages/merge-styles/src/transforms/kebabRules.test.ts new file mode 100644 index 00000000000000..7fe3d58730a820 --- /dev/null +++ b/packages/merge-styles/src/transforms/kebabRules.test.ts @@ -0,0 +1,34 @@ +import { kebabRules } from './kebabRules'; +import { expect } from 'chai'; + +describe('kebabRules', () => { + + it('can kebab the names', () => { + const rules = [ + 'backgroundColor', + '#cAcAcA' + ]; + + kebabRules(rules, 0); + + expect(rules).eqls([ + 'background-color', + '#cAcAcA' + ]); + }); + + it('can kebab webkit prefix', () => { + const rules = [ + 'WebkitFontSmoothing', + 'antialiased' + ]; + + kebabRules(rules, 0); + + expect(rules).eqls([ + '-webkit-font-smoothing', + 'antialiased' + ]); + }); + +}); diff --git a/packages/merge-styles/src/transforms/kebabRules.ts b/packages/merge-styles/src/transforms/kebabRules.ts new file mode 100644 index 00000000000000..33ad7b88e0aaaf --- /dev/null +++ b/packages/merge-styles/src/transforms/kebabRules.ts @@ -0,0 +1,6 @@ +export function kebabRules( + rulePairs: (string | number)[], + index: number +): void { + rulePairs[index] = (rulePairs[index] as string).replace(/([A-Z])/g, '-$1').toLowerCase(); +} \ No newline at end of file diff --git a/packages/merge-styles/src/transforms/prefixRules.test.ts b/packages/merge-styles/src/transforms/prefixRules.test.ts index 09c86a2bcb40f1..a6f99c41c76765 100644 --- a/packages/merge-styles/src/transforms/prefixRules.test.ts +++ b/packages/merge-styles/src/transforms/prefixRules.test.ts @@ -16,7 +16,7 @@ describe('prefixRules', () => { const rules = [rule, 'none']; setVendorSettings({ isWebkit: true }); - prefixRules(rules); + prefixRules(rules, 0); expect(rules).eql([ rule, 'none', @@ -30,7 +30,7 @@ describe('prefixRules', () => { const rules = [rule, 'none']; setVendorSettings({ isMoz: true }); - prefixRules(rules); + prefixRules(rules, 0); expect(rules).eql([ rule, 'none', '-moz-' + rule, 'none' @@ -43,7 +43,7 @@ describe('prefixRules', () => { const rules = [rule, 'none']; setVendorSettings({ isMs: true }); - prefixRules(rules); + prefixRules(rules, 0); expect(rules).eql([ rule, 'none', '-ms-' + rule, 'none' @@ -56,7 +56,7 @@ describe('prefixRules', () => { const rules = [rule, 'none']; setVendorSettings({ isOpera: true }); - prefixRules(rules); + prefixRules(rules, 0); expect(rules).eql([ rule, 'none', '-o-' + rule, 'none' diff --git a/packages/merge-styles/src/transforms/prefixRules.ts b/packages/merge-styles/src/transforms/prefixRules.ts index 5218488c1f902c..109fe3b089d875 100644 --- a/packages/merge-styles/src/transforms/prefixRules.ts +++ b/packages/merge-styles/src/transforms/prefixRules.ts @@ -5,13 +5,15 @@ const autoPrefixNames: { [key: string]: number } = { }; export function prefixRules( - rulePairs: string[] + rulePairs: (string | number)[], + index: number ): void { const vendorSettings = getVendorSettings(); - for (let nameIndex = 0, valueIndex = 1; nameIndex < rulePairs.length; nameIndex += 2, valueIndex += 2) { - const name = rulePairs[nameIndex]; - const value = rulePairs[valueIndex]; + const name = rulePairs[index]; + + if (autoPrefixNames[name]) { + const value = rulePairs[index + 1]; if (autoPrefixNames[name]) { if (vendorSettings.isWebkit) { @@ -28,4 +30,4 @@ export function prefixRules( } } } -} \ No newline at end of file +} diff --git a/packages/merge-styles/src/transforms/provideUnits.test.ts b/packages/merge-styles/src/transforms/provideUnits.test.ts index e2eb3e11f6978a..3e5d641b632b80 100644 --- a/packages/merge-styles/src/transforms/provideUnits.test.ts +++ b/packages/merge-styles/src/transforms/provideUnits.test.ts @@ -13,7 +13,7 @@ describe('provideUnits', () => { ].forEach((property: string) => { const testSet: (string | number)[] = [property, 1]; - provideUnits(testSet); + provideUnits(testSet, 0); expect(testSet).eql([property, '1px']); }); @@ -33,7 +33,11 @@ describe('provideUnits', () => { property + 'Bottom', 1 ]; - provideUnits(testSet); + provideUnits(testSet, 0); + provideUnits(testSet, 2); + provideUnits(testSet, 4); + provideUnits(testSet, 6); + provideUnits(testSet, 8); expect(testSet).eql([ property, '1px', @@ -51,7 +55,7 @@ describe('provideUnits', () => { 0 ]; - provideUnits(testSet); + provideUnits(testSet, 0); expect(testSet).eql(['opacity', 0]); }); diff --git a/packages/merge-styles/src/transforms/provideUnits.ts b/packages/merge-styles/src/transforms/provideUnits.ts index cd538438f78639..9b3c4b5fa2132f 100644 --- a/packages/merge-styles/src/transforms/provideUnits.ts +++ b/packages/merge-styles/src/transforms/provideUnits.ts @@ -1,12 +1,14 @@ -export function provideUnits(rulePairs: (string | number)[]): void { - for (let i = 0; i < rulePairs.length; i += 2) { - const name = rulePairs[i]; - const value = rulePairs[i + 1]; - if ( - name !== 'opacity' && - typeof value === 'number' - ) { - rulePairs[i + 1] = `${value}px`; - } +export function provideUnits( + rulePairs: (string | number)[], + index: number +): void { + const name = rulePairs[index]; + const value = rulePairs[index + 1]; + + if ( + name !== 'opacity' && + typeof value === 'number' + ) { + rulePairs[index + 1] = `${value}px`; } } diff --git a/packages/merge-styles/src/transforms/rtlifyRules.test.ts b/packages/merge-styles/src/transforms/rtlifyRules.test.ts index 3ce13494f28df0..e2ce99fd79ebb2 100644 --- a/packages/merge-styles/src/transforms/rtlifyRules.test.ts +++ b/packages/merge-styles/src/transforms/rtlifyRules.test.ts @@ -23,27 +23,32 @@ describe('rtlifyRules', () => { [['margin', '1 2'], ['margin', '1 2']], [['margin', '1 2 3'], ['margin', '1 2 3']], [['margin', '1 2 3 4'], ['margin', '1 4 3 2']], - [['marginLeft', '42'], ['marginRight', '42']], - [['marginRight', '42'], ['marginLeft', '42']], + [['margin-left', '42'], ['margin-right', '42']], + [['margin-right', '42'], ['margin-left', '42']], [['padding', '42'], ['padding', '42']], [['padding', '1 2'], ['padding', '1 2']], [['padding', '1 2 3'], ['padding', '1 2 3']], [['padding', '1 2 3 4'], ['padding', '1 4 3 2']], - [['paddingLeft', '42'], ['paddingRight', '42']], - [['paddingRight', '42'], ['paddingLeft', '42']], + [['padding-left', '42'], ['padding-right', '42']], + [['padding-right', '42'], ['padding-left', '42']], [['cursor', 'w-resize'], ['cursor', 'e-resize']], [['cursor', 'sw-resize'], ['cursor', 'se-resize']], [['cursor', 'nw-resize'], ['cursor', 'ne-resize']], [['left', '42px /*noflip*/'], ['left', '42px /*noflip*/']], - [['boxShadow', '42px 0 red'], ['boxShadow', '-42px 0 red']], - [['boxShadow', '-42px 0 red'], ['boxShadow', '42px 0 red']] - ].forEach((test: string[][]) => expect(rtlifyRules(test[0])).eqls(test[1])); + [['box-shadow', '42px 0 red'], ['box-shadow', '-42px 0 red']], + [['box-shadow', '-42px 0 red'], ['box-shadow', '42px 0 red']] + ].forEach((test: string[][]) => { + rtlifyRules(test[0], 0); + expect(test[0]).eqls(test[1]); + }); }); it('does not flip an unflippable cursor', () => { const rules = ['cursor', 'hand']; - expect(rtlifyRules(rules)).eqls(['cursor', 'hand']); + rtlifyRules(rules, 0); + + expect(rules).eqls(['cursor', 'hand']); }); }); diff --git a/packages/merge-styles/src/transforms/rtlifyRules.ts b/packages/merge-styles/src/transforms/rtlifyRules.ts index cd1c178f1c8a30..46a3bca8c33599 100644 --- a/packages/merge-styles/src/transforms/rtlifyRules.ts +++ b/packages/merge-styles/src/transforms/rtlifyRules.ts @@ -27,41 +27,40 @@ export function getRTL(): boolean { return _rtl; } -export function rtlifyRules(rulePairs: string[]): string[] { +export function rtlifyRules( + rulePairs: (string | number)[], + index: number +): void { if (getRTL()) { - for (let nameIndex = 0, valueIndex = 1; nameIndex < rulePairs.length; nameIndex += 2, valueIndex += 2) { - const name = rulePairs[nameIndex]; - const value = rulePairs[valueIndex]; + const name = rulePairs[index] as string; + const value = rulePairs[index + 1] as string; - if (value.indexOf(NO_FLIP) >= 0) { - continue; - } else if (name.indexOf('Left') >= 0) { - rulePairs[nameIndex] = name.replace('Left', 'Right'); - } else if (name.indexOf('Right') >= 0) { - rulePairs[nameIndex] = name.replace('Right', 'Left'); - } else if (String(value).indexOf('left') >= 0) { - rulePairs[valueIndex] = value.replace('left', 'right'); - } else if (String(value).indexOf('right') >= 0) { - rulePairs[valueIndex] = value.replace('right', 'left'); - } else if (_nameReplacements[name]) { - rulePairs[nameIndex] = _nameReplacements[name]; - } else if (_valueReplacements[value]) { - rulePairs[valueIndex] = _valueReplacements[value]; - } else { - switch (name) { - case 'margin': - case 'padding': - rulePairs[valueIndex] = flipQuad(value); - break; - case 'boxShadow': - rulePairs[valueIndex] = negateNum(value, 0); - break; - } + if (value.indexOf(NO_FLIP) >= 0) { + return; + } else if (name.indexOf('left') >= 0) { + rulePairs[index] = name.replace('left', 'right'); + } else if (name.indexOf('right') >= 0) { + rulePairs[index] = name.replace('right', 'left'); + } else if (String(value).indexOf('left') >= 0) { + rulePairs[index + 1] = value.replace('left', 'right'); + } else if (String(value).indexOf('right') >= 0) { + rulePairs[index + 1] = value.replace('right', 'left'); + } else if (_nameReplacements[name]) { + rulePairs[index] = _nameReplacements[name]; + } else if (_valueReplacements[value]) { + rulePairs[index + 1] = _valueReplacements[value]; + } else { + switch (name) { + case 'margin': + case 'padding': + rulePairs[index + 1] = flipQuad(value); + break; + case 'box-shadow': + rulePairs[index + 1] = negateNum(value, 0); + break; } } } - - return rulePairs; } function negateNum(value: string, partIndex: number): string { diff --git a/packages/merge-styles/tsconfig.json b/packages/merge-styles/tsconfig.json index 55327985569192..d8bc289af26e36 100644 --- a/packages/merge-styles/tsconfig.json +++ b/packages/merge-styles/tsconfig.json @@ -10,7 +10,7 @@ "declaration": true, "sourceMap": true, "experimentalDecorators": true, - "noImplicitAny": true, + "importHelpers": true, "strict": true, "forceConsistentCasingInFileNames": true, "moduleResolution": "node", diff --git a/packages/merge-styles/webpack.config.js b/packages/merge-styles/webpack.config.js index 0806676d047e04..a85316c2121340 100644 --- a/packages/merge-styles/webpack.config.js +++ b/packages/merge-styles/webpack.config.js @@ -28,10 +28,10 @@ let webpackConfig = { externals: [ { - // 'tslib': { - // commonjs: 'tslib', - // amd: 'tslib' - // } + 'tslib': { + commonjs: 'tslib', + amd: 'tslib' + } } ], From 88bac211f59750f1ef26c1e7c4c815c3d018d81a Mon Sep 17 00:00:00 2001 From: David Zearing Date: Fri, 18 Aug 2017 14:48:15 -0700 Subject: [PATCH 16/17] Updating documentation. --- packages/merge-styles/README.md | 34 +++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/packages/merge-styles/README.md b/packages/merge-styles/README.md index ed3c6dfaf0e5d5..b39128efd1b059 100644 --- a/packages/merge-styles/README.md +++ b/packages/merge-styles/README.md @@ -6,9 +6,11 @@ The library was built for speed and size; the entire package is 2.62k gzipped. I The basic idea is to provide a method which can take in one or more style objects css styling javascript objects representing the styles for a given element, and return a single class name. If the same set of styling is passed in, the same name returns and nothing is re-registered. -This has a number of benefits over traditional build time staticly produced css: +## Why not static solutions like scss? -* Only register classes that are needed, when they're needed, reducing the overall selector count. +Defining rules at runtime has a number of benefits over traditional build time staticly produced css: + +* Only register classes that are needed, when they're needed, reducing the overall selector count and improving TTG. * Dynamically create new class permutations based on contextual theming requirements. (Use a different theme inside of a DIV without downloading multiple copies of the css rule definitions.) @@ -16,7 +18,7 @@ This has a number of benefits over traditional build time staticly produced css: * Allow control libraries to merge customized styling in with their rules, avoiding complexities like css selector specificity. -* Simplify RTL processing; lefts become rights in RTL, in the actual rules. No complexity like `html[dir=rtl]` prefixes necessary, which alleviates unexpected specificity bugs. +* Simplify RTL processing; lefts become rights in RTL, in the actual rules. No complexity like `html[dir=rtl]` prefixes necessary, which alleviates unexpected specificity bugs. (You can use `/* noflip */` comments to avoid flipping if needed.) * Reduce bundle size. Automatically handles vendor prefixing, unit providing, RTL flipping, and margin/padding expansion (e.g. margin will automatically expand out to margin TRBL, so that we avoid specificity problems when merging things together.) @@ -24,19 +26,23 @@ This has a number of benefits over traditional build time staticly produced css: * TypeScript type safety; spell "background" wrong and get build breaks. -The api surfaces consists of TypeScript interfaces and a few important methods: +## What tradeoffs are there? Are there downsides to using JavaScript to process styling? -`mergeStyles(..args[]` - Takes in one or more style objects, merges them in the right order, and produces a single css class name which can be injected into any component. +In static solutions, there is very little runtime evaluation required; everything is -`mergeStyleSet` - Takes in one or more style set objects, each consisting of a set of areas, each which will produce a class name. Using this is analogous to calling mergeStyles for each property in the object, but ensures we maintain the set ordering when multiple style sets are merged. +# API -`concatStyleSet` - In some cases you simply need to combine style sets, without actually generating class names (it is costs in performance to generate class names.) This tool returns a single set merging many together. +The api surfaces consists of 3 methods and a handful of interfaces: -## Vocabulary +`mergeStyles(..args[]: IStyle[]): string` - Takes in one or more style objects, merges them in the right order, and produces a single css class name which can be injected into any component. + +`mergeStyleSet(...args[]: IStyleSet[]): { [key: string]: string }` - Takes in one or more style set objects, each consisting of a set of areas, each which will produce a class name. Using this is analogous to calling mergeStyles for each property in the object, but ensures we maintain the set ordering when multiple style sets are merged. -Let's clear up a few definitions before we start; +`concatStyleSet(...args[]: IStyleSet[]): IStyleSet` - In some cases you simply need to combine style sets, without actually generating class names (it is costs in performance to generate class names.) This tool returns a single set merging many together. + +## Vocabulary -A *style object* represents the collection of css rules, except that the names are camelCased rather than kebab-cased. Example: +A **style object** represents the collection of css rules, except that the names are camelCased rather than kebab-cased. Example: ```tsx let style = { @@ -45,7 +51,7 @@ let style = { }; ``` -Additionally, *style objects* can contain selectors under the `selectors` property: +Additionally, **style objects** can contain selectors under the `selectors` property: ```tsx let style = { @@ -60,7 +66,7 @@ let style = { }; ``` -A *style set* represents a map of area to style object. When building a component, you need to generate a class name for each element that requires styling. You would defint this in a *style set*. +A **style set** represents a map of area to style object. When building a component, you need to generate a class name for each element that requires styling. You would defint this in a **style set**. ```tsx let styleSet = { @@ -71,7 +77,7 @@ let styleSet = { ## Basic usage -When building a component, you will need a *style set* map of class names to inject into your elements' class attributes. +When building a component, you will need a **style set** map of class names to inject into your elements' class attributes. The recommended pattern is to provide the classnames in a separate function, typically in a separate file `ComponentName.classNames.ts`. @@ -107,7 +113,7 @@ export const getClassNames = () => { }; ``` -The class map can then be used in a component: +The class map can then be used in a component. The example below illustrates a React component, but the library can be used with any framework. ```tsx import { getClassNames } from './MyComponent.classNames'; From 111af6973367c4784a57f4926839b9579a70363c Mon Sep 17 00:00:00 2001 From: David Zearing Date: Fri, 18 Aug 2017 14:58:18 -0700 Subject: [PATCH 17/17] Minor grammar fixes. --- packages/merge-styles/README.md | 86 ++++++++++++++++++++++++++++----- 1 file changed, 75 insertions(+), 11 deletions(-) diff --git a/packages/merge-styles/README.md b/packages/merge-styles/README.md index b39128efd1b059..8ab309149676ff 100644 --- a/packages/merge-styles/README.md +++ b/packages/merge-styles/README.md @@ -1,12 +1,12 @@ # [merge-styles](http://dev.office.com/fabric) -The `merge-styles` library provides a number of utilities for loading styles through javascript. It is designed to make it simple to style components through javascript. It generates css rules, rather than using inline styling, to ensure we can use css features like pseudo selectors (:hover) and parent/child selectors (media queries). +The `merge-styles` library provides utilities for loading styles through javascript. It is designed to make it simple to style components through javascript. It generates css classes, rather than using inline styling, to ensure we can use css features like pseudo selectors (:hover) and parent/child selectors (media queries). -The library was built for speed and size; the entire package is 2.62k gzipped. It has no dependencies. +The library was built for speed and size; the entire package is 2.62k gzipped. It has no dependencies other than `tslib`. The basic idea is to provide a method which can take in one or more style objects css styling javascript objects representing the styles for a given element, and return a single class name. If the same set of styling is passed in, the same name returns and nothing is re-registered. -## Why not static solutions like scss? +## Motivation Defining rules at runtime has a number of benefits over traditional build time staticly produced css: @@ -28,7 +28,9 @@ Defining rules at runtime has a number of benefits over traditional build time s ## What tradeoffs are there? Are there downsides to using JavaScript to process styling? -In static solutions, there is very little runtime evaluation required; everything is +In static solutions, there is very little runtime evaluation required; everything is injected as-is. Things like auto prefixing and language specific processing like sass mixins are all evaluated at build time. + +In runtime styling, much of this is evaluated in the browser, so you are paying a cost in doing this. However, with performance optimizations like memoization, you can minimize this quite a bit, and you gain all of the robustness enumerated above. # API @@ -90,7 +92,7 @@ export interface IComponentClassNames { buttonIcon: string; } -export const getClassNames = () => { +export const getClassNames = (): IComponentClassNames => { return mergeStyleSets({ root: { background: 'red' @@ -99,11 +101,6 @@ export const getClassNames = () => { button: { backgroundColor: 'green', - selectors: { - ':hover': { - backgroundColor: 'blue' - } - } }, buttonIcon: { @@ -113,7 +110,7 @@ export const getClassNames = () => { }; ``` -The class map can then be used in a component. The example below illustrates a React component, but the library can be used with any framework. +The class map can then be used in a component: ```tsx import { getClassNames } from './MyComponent.classNames'; @@ -131,6 +128,71 @@ export const MyComponent = () => { }; ``` +## Selectors + +Custom selectors can be defined within `IStyle` definitions under the `selectors` section: + +```tsx +{ + background: 'red', + selectors: { + ':hover': { + background: 'green' + } + } +} +``` + +By default, the rule will be appended to the current selector scope. That is, in the above scenario, there will be 2 rules inserted when using `mergeRules`: + +```css +.css-0 { background: red; } +.css-0:hover { background: green; } +``` + +In some cases, you may need to use parent or child selectors. To do so, you can define a selector from scratch and use the `&` character to represent the generated class name. When using the `&`, the current scope is ignored. Example: + +```tsx +{ + selectors: { + // selector relative to parent + '.ms-Fabric.is-focusVisible &': { + background: 'red' + } + // selector for child + '& .child' { + background: 'green' + } + } +} +``` + +This would register the rules: + +```css +.ms-Fabric.is-focusVisible .css-0 { background: red; } +.css-0 .child { background: green; } +``` + +## Custom class names + +By default class names that are generated will use the prefix `css-` followed by a number, creating unique rules where needed. + +While this prefix is fine, sometimes a more readable prefix is desired. You can pass in a `displayName` to resolve this: + +```tsx +{ + displayName: 'MyComponent', + background: 'red' +} +``` + +This generates: + +```css +.MyComponent-0 { background: red; } +``` + ## Managing conditionals and states Style objects can be represented by a simple object, but also can be an array of the objects. The merge functions will handle arrays and merge things together in the given order. They will also ignore falsey values, allowing you to conditionalize the results. @@ -239,3 +301,5 @@ Caveats for server-side rendering (TODOs): * Until all Fabric components use the merge-styles library, this will only return a subset of the styling. Also a known limitation and work in progress. * The rehydration logic has not yet been implemented, so we may run into issues when you rehydrate. + +* Only components which USE mergeStyles will have their css included. In Fabric, not all components have been converted from using SASS yet.