diff --git a/.gitignore b/.gitignore index e9b6147..d687bd2 100644 --- a/.gitignore +++ b/.gitignore @@ -10,7 +10,6 @@ build/ # Application var -static # Python Package dist/ @@ -43,4 +42,4 @@ $virtualenv.tar.gz *.pot bin -.vscode/ \ No newline at end of file +.vscode/ diff --git a/package-lock.json b/package-lock.json index dfa3f40..46ec4f4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "wagtailmodelchoosers", - "version": "0.1.2", + "version": "2.0.0b1", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -16,7 +16,7 @@ "integrity": "sha1-x1K9IQvvZ5UBtsbLf8hPj0cVjMQ=", "dev": true, "requires": { - "acorn": "4.0.11" + "acorn": "^4.0.3" }, "dependencies": { "acorn": { @@ -33,7 +33,7 @@ "integrity": "sha1-r9+UiPsezvyDSPb7IvRk4ypYs2s=", "dev": true, "requires": { - "acorn": "3.3.0" + "acorn": "^3.0.4" }, "dependencies": { "acorn": { @@ -50,8 +50,8 @@ "integrity": "sha1-hlWl2G0IJJhcxHGh2RP7Zymg7Eg=", "dev": true, "requires": { - "co": "4.6.0", - "json-stable-stringify": "1.0.1" + "co": "^4.6.0", + "json-stable-stringify": "^1.0.1" } }, "ajv-keywords": { @@ -66,9 +66,9 @@ "integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=", "dev": true, "requires": { - "kind-of": "3.2.0", - "longest": "1.0.1", - "repeat-string": "1.6.1" + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" } }, "alphanum-sort": { @@ -101,8 +101,8 @@ "integrity": "sha1-o+Uvo5FoyCX/V7AkgSbOWo/5VQc=", "dev": true, "requires": { - "arrify": "1.0.1", - "micromatch": "2.3.11" + "arrify": "^1.0.0", + "micromatch": "^2.1.5" } }, "argparse": { @@ -111,7 +111,7 @@ "integrity": "sha1-c9g7wmP4bpf4zE9rrhsOkKfSLIY=", "dev": true, "requires": { - "sprintf-js": "1.0.3" + "sprintf-js": "~1.0.2" } }, "arr-diff": { @@ -120,7 +120,7 @@ "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", "dev": true, "requires": { - "arr-flatten": "1.0.3" + "arr-flatten": "^1.0.1" } }, "arr-flatten": { @@ -135,7 +135,7 @@ "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", "dev": true, "requires": { - "array-uniq": "1.0.3" + "array-uniq": "^1.0.1" } }, "array-uniq": { @@ -156,8 +156,8 @@ "integrity": "sha1-VWpcU2LAhkgyPdrrnenRS8GGTJA=", "dev": true, "requires": { - "define-properties": "1.1.2", - "es-abstract": "1.7.0" + "define-properties": "^1.1.2", + "es-abstract": "^1.7.0" } }, "arrify": { @@ -177,9 +177,9 @@ "integrity": "sha1-SLokC0WpKA6UdImQull9IWYX/UA=", "dev": true, "requires": { - "bn.js": "4.11.6", - "inherits": "2.0.3", - "minimalistic-assert": "1.0.0" + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" } }, "assert": { @@ -197,7 +197,7 @@ "integrity": "sha1-EBPRBRBH3TIP4k5JTVxm7K9hR9k=", "dev": true, "requires": { - "lodash": "4.17.4" + "lodash": "^4.14.0" } }, "async-each": { @@ -212,12 +212,12 @@ "integrity": "sha1-Hb0cg1ZY41zj+ZhAmdsAWFx4IBQ=", "dev": true, "requires": { - "browserslist": "1.7.7", - "caniuse-db": "1.0.30000662", - "normalize-range": "0.1.2", - "num2fraction": "1.2.2", - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0" + "browserslist": "^1.7.6", + "caniuse-db": "^1.0.30000634", + "normalize-range": "^0.1.2", + "num2fraction": "^1.2.2", + "postcss": "^5.2.16", + "postcss-value-parser": "^3.2.3" } }, "babel-code-frame": { @@ -226,9 +226,9 @@ "integrity": "sha1-AnYgvuVnqIwyVhV05/0IAdMxGOQ=", "dev": true, "requires": { - "chalk": "1.1.3", - "esutils": "2.0.2", - "js-tokens": "3.0.1" + "chalk": "^1.1.0", + "esutils": "^2.0.2", + "js-tokens": "^3.0.0" } }, "babel-core": { @@ -237,25 +237,25 @@ "integrity": "sha1-jEKFZNzh4fQfszfsNPTDsCK1rYM=", "dev": true, "requires": { - "babel-code-frame": "6.22.0", - "babel-generator": "6.24.1", - "babel-helpers": "6.24.1", - "babel-messages": "6.23.0", - "babel-register": "6.24.1", - "babel-runtime": "6.23.0", - "babel-template": "6.24.1", - "babel-traverse": "6.24.1", - "babel-types": "6.24.1", - "babylon": "6.17.0", - "convert-source-map": "1.5.0", - "debug": "2.6.4", - "json5": "0.5.1", - "lodash": "4.17.4", - "minimatch": "3.0.3", - "path-is-absolute": "1.0.1", - "private": "0.1.7", - "slash": "1.0.0", - "source-map": "0.5.6" + "babel-code-frame": "^6.22.0", + "babel-generator": "^6.24.1", + "babel-helpers": "^6.24.1", + "babel-messages": "^6.23.0", + "babel-register": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1", + "babylon": "^6.11.0", + "convert-source-map": "^1.1.0", + "debug": "^2.1.1", + "json5": "^0.5.0", + "lodash": "^4.2.0", + "minimatch": "^3.0.2", + "path-is-absolute": "^1.0.0", + "private": "^0.1.6", + "slash": "^1.0.0", + "source-map": "^0.5.0" } }, "babel-generator": { @@ -264,14 +264,14 @@ "integrity": "sha1-5xX0hsWN7SVknYiJRNUqoHxdlJc=", "dev": true, "requires": { - "babel-messages": "6.23.0", - "babel-runtime": "6.23.0", - "babel-types": "6.24.1", - "detect-indent": "4.0.0", - "jsesc": "1.3.0", - "lodash": "4.17.4", - "source-map": "0.5.6", - "trim-right": "1.0.1" + "babel-messages": "^6.23.0", + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1", + "detect-indent": "^4.0.0", + "jsesc": "^1.3.0", + "lodash": "^4.2.0", + "source-map": "^0.5.0", + "trim-right": "^1.0.1" } }, "babel-helper-builder-binary-assignment-operator-visitor": { @@ -280,9 +280,9 @@ "integrity": "sha1-zORReto1b0IgvK6KAsKzRvmlZmQ=", "dev": true, "requires": { - "babel-helper-explode-assignable-expression": "6.24.1", - "babel-runtime": "6.23.0", - "babel-types": "6.24.1" + "babel-helper-explode-assignable-expression": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" } }, "babel-helper-builder-react-jsx": { @@ -291,9 +291,9 @@ "integrity": "sha1-CteRfjPI11HmRtrKTnfMGTd9LLw=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-types": "6.24.1", - "esutils": "2.0.2" + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1", + "esutils": "^2.0.0" } }, "babel-helper-call-delegate": { @@ -302,10 +302,10 @@ "integrity": "sha1-7Oaqzdx25Bw0YfiL/Fdb0Nqi340=", "dev": true, "requires": { - "babel-helper-hoist-variables": "6.24.1", - "babel-runtime": "6.23.0", - "babel-traverse": "6.24.1", - "babel-types": "6.24.1" + "babel-helper-hoist-variables": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" } }, "babel-helper-define-map": { @@ -314,10 +314,10 @@ "integrity": "sha1-epdH8ljYlH0y1RX2qhx70CIEoIA=", "dev": true, "requires": { - "babel-helper-function-name": "6.24.1", - "babel-runtime": "6.23.0", - "babel-types": "6.24.1", - "lodash": "4.17.4" + "babel-helper-function-name": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1", + "lodash": "^4.2.0" } }, "babel-helper-explode-assignable-expression": { @@ -326,9 +326,9 @@ "integrity": "sha1-8luCz33BBDPFX3BZLVdGQArCLKo=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-traverse": "6.24.1", - "babel-types": "6.24.1" + "babel-runtime": "^6.22.0", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" } }, "babel-helper-function-name": { @@ -337,11 +337,11 @@ "integrity": "sha1-00dbjAPtmCQqJbSDUasYOZ01gKk=", "dev": true, "requires": { - "babel-helper-get-function-arity": "6.24.1", - "babel-runtime": "6.23.0", - "babel-template": "6.24.1", - "babel-traverse": "6.24.1", - "babel-types": "6.24.1" + "babel-helper-get-function-arity": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" } }, "babel-helper-get-function-arity": { @@ -350,8 +350,8 @@ "integrity": "sha1-j3eCqpNAfEHTqlCQj4mwMbG2hT0=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-types": "6.24.1" + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" } }, "babel-helper-hoist-variables": { @@ -360,8 +360,8 @@ "integrity": "sha1-HssnaJydJVE+rbyZFKc/VAi+enY=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-types": "6.24.1" + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" } }, "babel-helper-optimise-call-expression": { @@ -370,8 +370,8 @@ "integrity": "sha1-96E0J7qfc/j0+pk8VKl4gtEkQlc=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-types": "6.24.1" + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" } }, "babel-helper-regex": { @@ -380,9 +380,9 @@ "integrity": "sha1-024i+rEAjXnYhkjjIRaGgShFbOg=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-types": "6.24.1", - "lodash": "4.17.4" + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1", + "lodash": "^4.2.0" } }, "babel-helper-remap-async-to-generator": { @@ -391,11 +391,11 @@ "integrity": "sha1-XsWBgnrXI/7N04HxySg5BnbkVRs=", "dev": true, "requires": { - "babel-helper-function-name": "6.24.1", - "babel-runtime": "6.23.0", - "babel-template": "6.24.1", - "babel-traverse": "6.24.1", - "babel-types": "6.24.1" + "babel-helper-function-name": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" } }, "babel-helper-replace-supers": { @@ -404,12 +404,12 @@ "integrity": "sha1-v22/5Dk40XNpohPKiov3S2qQqxo=", "dev": true, "requires": { - "babel-helper-optimise-call-expression": "6.24.1", - "babel-messages": "6.23.0", - "babel-runtime": "6.23.0", - "babel-template": "6.24.1", - "babel-traverse": "6.24.1", - "babel-types": "6.24.1" + "babel-helper-optimise-call-expression": "^6.24.1", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" } }, "babel-helpers": { @@ -418,8 +418,8 @@ "integrity": "sha1-NHHenK7DiOXIUOWX5Yom3fN2ArI=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-template": "6.24.1" + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" } }, "babel-loader": { @@ -428,10 +428,10 @@ "integrity": "sha1-CzQRLVsHSKjc2/Uaz2+b1C1QuMo=", "dev": true, "requires": { - "find-cache-dir": "0.1.1", - "loader-utils": "0.2.17", - "mkdirp": "0.5.1", - "object-assign": "4.1.1" + "find-cache-dir": "^0.1.1", + "loader-utils": "^0.2.16", + "mkdirp": "^0.5.1", + "object-assign": "^4.0.1" } }, "babel-messages": { @@ -440,7 +440,7 @@ "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", "dev": true, "requires": { - "babel-runtime": "6.23.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-check-es2015-constants": { @@ -449,7 +449,7 @@ "integrity": "sha1-NRV7EBQm/S/9PaP3XH0ekYNbv4o=", "dev": true, "requires": { - "babel-runtime": "6.23.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-syntax-async-functions": { @@ -488,9 +488,9 @@ "integrity": "sha1-ZTbjeK/2yx1VF6wOQOs+n8jQh2E=", "dev": true, "requires": { - "babel-helper-remap-async-to-generator": "6.24.1", - "babel-plugin-syntax-async-functions": "6.13.0", - "babel-runtime": "6.23.0" + "babel-helper-remap-async-to-generator": "^6.24.1", + "babel-plugin-syntax-async-functions": "^6.8.0", + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-es2015-arrow-functions": { @@ -499,7 +499,7 @@ "integrity": "sha1-RSaSy3EdX3ncf4XkQM5BufJE0iE=", "dev": true, "requires": { - "babel-runtime": "6.23.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-es2015-block-scoped-functions": { @@ -508,7 +508,7 @@ "integrity": "sha1-u8UbSflk1wy42OC5ToICRs46YUE=", "dev": true, "requires": { - "babel-runtime": "6.23.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-es2015-block-scoping": { @@ -517,11 +517,11 @@ "integrity": "sha1-dsKV3DpHQbFmWt/TFnIV3P8ypXY=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-template": "6.24.1", - "babel-traverse": "6.24.1", - "babel-types": "6.24.1", - "lodash": "4.17.4" + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1", + "lodash": "^4.2.0" } }, "babel-plugin-transform-es2015-classes": { @@ -530,15 +530,15 @@ "integrity": "sha1-WkxYpQyclGHlZLSyo7+ryXolhNs=", "dev": true, "requires": { - "babel-helper-define-map": "6.24.1", - "babel-helper-function-name": "6.24.1", - "babel-helper-optimise-call-expression": "6.24.1", - "babel-helper-replace-supers": "6.24.1", - "babel-messages": "6.23.0", - "babel-runtime": "6.23.0", - "babel-template": "6.24.1", - "babel-traverse": "6.24.1", - "babel-types": "6.24.1" + "babel-helper-define-map": "^6.24.1", + "babel-helper-function-name": "^6.24.1", + "babel-helper-optimise-call-expression": "^6.24.1", + "babel-helper-replace-supers": "^6.24.1", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" } }, "babel-plugin-transform-es2015-computed-properties": { @@ -547,8 +547,8 @@ "integrity": "sha1-b+Ko0WiV1WNPTNmZttNICjCBWbM=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-template": "6.24.1" + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" } }, "babel-plugin-transform-es2015-destructuring": { @@ -557,7 +557,7 @@ "integrity": "sha1-mXux8auWf2gtKwh2/jWNYOdlxW0=", "dev": true, "requires": { - "babel-runtime": "6.23.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-es2015-duplicate-keys": { @@ -566,8 +566,8 @@ "integrity": "sha1-c+s9MQypaePvnskcU3QabxV2Qj4=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-types": "6.24.1" + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" } }, "babel-plugin-transform-es2015-for-of": { @@ -576,7 +576,7 @@ "integrity": "sha1-9HyVsrYT3x0+zC/bdXNiPHUkhpE=", "dev": true, "requires": { - "babel-runtime": "6.23.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-es2015-function-name": { @@ -585,9 +585,9 @@ "integrity": "sha1-g0yJhTvDaxrw86TF26qU/Y6sqos=", "dev": true, "requires": { - "babel-helper-function-name": "6.24.1", - "babel-runtime": "6.23.0", - "babel-types": "6.24.1" + "babel-helper-function-name": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" } }, "babel-plugin-transform-es2015-literals": { @@ -596,7 +596,7 @@ "integrity": "sha1-T1SgLWzWbPkVKAAZox0xklN3yi4=", "dev": true, "requires": { - "babel-runtime": "6.23.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-es2015-modules-amd": { @@ -605,9 +605,9 @@ "integrity": "sha1-Oz5UAXI5hC1tGcMBHEvS8AoA0VQ=", "dev": true, "requires": { - "babel-plugin-transform-es2015-modules-commonjs": "6.24.1", - "babel-runtime": "6.23.0", - "babel-template": "6.24.1" + "babel-plugin-transform-es2015-modules-commonjs": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" } }, "babel-plugin-transform-es2015-modules-commonjs": { @@ -616,10 +616,10 @@ "integrity": "sha1-0+MQtA72ZKNmIiAAl8bUQCmPK/4=", "dev": true, "requires": { - "babel-plugin-transform-strict-mode": "6.24.1", - "babel-runtime": "6.23.0", - "babel-template": "6.24.1", - "babel-types": "6.24.1" + "babel-plugin-transform-strict-mode": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-types": "^6.24.1" } }, "babel-plugin-transform-es2015-modules-systemjs": { @@ -628,9 +628,9 @@ "integrity": "sha1-/4mhQrkRmpBhlfXxBuzzBdlAfSM=", "dev": true, "requires": { - "babel-helper-hoist-variables": "6.24.1", - "babel-runtime": "6.23.0", - "babel-template": "6.24.1" + "babel-helper-hoist-variables": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" } }, "babel-plugin-transform-es2015-modules-umd": { @@ -639,9 +639,9 @@ "integrity": "sha1-rJl+YoXNGO1hdq22B9YCNErThGg=", "dev": true, "requires": { - "babel-plugin-transform-es2015-modules-amd": "6.24.1", - "babel-runtime": "6.23.0", - "babel-template": "6.24.1" + "babel-plugin-transform-es2015-modules-amd": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" } }, "babel-plugin-transform-es2015-object-super": { @@ -650,8 +650,8 @@ "integrity": "sha1-JM72muIcuDp/hgPa0CH1cusnj40=", "dev": true, "requires": { - "babel-helper-replace-supers": "6.24.1", - "babel-runtime": "6.23.0" + "babel-helper-replace-supers": "^6.24.1", + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-es2015-parameters": { @@ -660,12 +660,12 @@ "integrity": "sha1-V6w1GrScrxSpfNE7CfZv3wpiXys=", "dev": true, "requires": { - "babel-helper-call-delegate": "6.24.1", - "babel-helper-get-function-arity": "6.24.1", - "babel-runtime": "6.23.0", - "babel-template": "6.24.1", - "babel-traverse": "6.24.1", - "babel-types": "6.24.1" + "babel-helper-call-delegate": "^6.24.1", + "babel-helper-get-function-arity": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" } }, "babel-plugin-transform-es2015-shorthand-properties": { @@ -674,8 +674,8 @@ "integrity": "sha1-JPh11nIch2YbvZmkYi5R8U3jiqA=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-types": "6.24.1" + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" } }, "babel-plugin-transform-es2015-spread": { @@ -684,7 +684,7 @@ "integrity": "sha1-1taKmfia7cRTbIGlQujdnxdG+NE=", "dev": true, "requires": { - "babel-runtime": "6.23.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-es2015-sticky-regex": { @@ -693,9 +693,9 @@ "integrity": "sha1-AMHNsaynERLN8M9hJsLta0V8zbw=", "dev": true, "requires": { - "babel-helper-regex": "6.24.1", - "babel-runtime": "6.23.0", - "babel-types": "6.24.1" + "babel-helper-regex": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" } }, "babel-plugin-transform-es2015-template-literals": { @@ -704,7 +704,7 @@ "integrity": "sha1-qEs0UPfp+PH2g51taH2oS7EjbY0=", "dev": true, "requires": { - "babel-runtime": "6.23.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-es2015-typeof-symbol": { @@ -713,7 +713,7 @@ "integrity": "sha1-3sCfHN3/lLUqxz1QXITfWdzOs3I=", "dev": true, "requires": { - "babel-runtime": "6.23.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-es2015-unicode-regex": { @@ -722,9 +722,9 @@ "integrity": "sha1-04sS9C6nMj9yk4fxinxa4frrNek=", "dev": true, "requires": { - "babel-helper-regex": "6.24.1", - "babel-runtime": "6.23.0", - "regexpu-core": "2.0.0" + "babel-helper-regex": "^6.24.1", + "babel-runtime": "^6.22.0", + "regexpu-core": "^2.0.0" } }, "babel-plugin-transform-exponentiation-operator": { @@ -733,9 +733,9 @@ "integrity": "sha1-KrDJx/MJj6SJB3cruBP+QejeOg4=", "dev": true, "requires": { - "babel-helper-builder-binary-assignment-operator-visitor": "6.24.1", - "babel-plugin-syntax-exponentiation-operator": "6.13.0", - "babel-runtime": "6.23.0" + "babel-helper-builder-binary-assignment-operator-visitor": "^6.24.1", + "babel-plugin-syntax-exponentiation-operator": "^6.8.0", + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-flow-strip-types": { @@ -744,8 +744,8 @@ "integrity": "sha1-hMtnKTXUNxT9wyvOhFaNh0Qc988=", "dev": true, "requires": { - "babel-plugin-syntax-flow": "6.18.0", - "babel-runtime": "6.23.0" + "babel-plugin-syntax-flow": "^6.18.0", + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-react-display-name": { @@ -754,7 +754,7 @@ "integrity": "sha1-Q5iRDDWEQdxM7xh4cmTQQS7Tazc=", "dev": true, "requires": { - "babel-runtime": "6.23.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-react-jsx": { @@ -763,9 +763,9 @@ "integrity": "sha1-hAoCjn30YN/DotKfDA2R9jduZqM=", "dev": true, "requires": { - "babel-helper-builder-react-jsx": "6.24.1", - "babel-plugin-syntax-jsx": "6.18.0", - "babel-runtime": "6.23.0" + "babel-helper-builder-react-jsx": "^6.24.1", + "babel-plugin-syntax-jsx": "^6.8.0", + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-react-jsx-self": { @@ -774,8 +774,8 @@ "integrity": "sha1-322AqdomEqEh5t3XVYvL7PBuY24=", "dev": true, "requires": { - "babel-plugin-syntax-jsx": "6.18.0", - "babel-runtime": "6.23.0" + "babel-plugin-syntax-jsx": "^6.8.0", + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-react-jsx-source": { @@ -784,8 +784,8 @@ "integrity": "sha1-ZqwSFT9c0tF7PBkmj0vwGX9E7NY=", "dev": true, "requires": { - "babel-plugin-syntax-jsx": "6.18.0", - "babel-runtime": "6.23.0" + "babel-plugin-syntax-jsx": "^6.8.0", + "babel-runtime": "^6.22.0" } }, "babel-plugin-transform-regenerator": { @@ -803,8 +803,8 @@ "integrity": "sha1-1fr3qleKZbvlkc9e2uBKDGcCB1g=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-types": "6.24.1" + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" } }, "babel-polyfill": { @@ -813,9 +813,9 @@ "integrity": "sha1-g2TKYt+Or7gwSZ9pkXdGbDsDSZ0=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "core-js": "2.4.1", - "regenerator-runtime": "0.10.4" + "babel-runtime": "^6.22.0", + "core-js": "^2.4.0", + "regenerator-runtime": "^0.10.0" }, "dependencies": { "core-js": { @@ -832,35 +832,35 @@ "integrity": "sha1-yOAqO8x3kvI83taOA1W51MKPD3o=", "dev": true, "requires": { - "babel-plugin-check-es2015-constants": "6.22.0", - "babel-plugin-syntax-trailing-function-commas": "6.22.0", - "babel-plugin-transform-async-to-generator": "6.24.1", - "babel-plugin-transform-es2015-arrow-functions": "6.22.0", - "babel-plugin-transform-es2015-block-scoped-functions": "6.22.0", - "babel-plugin-transform-es2015-block-scoping": "6.24.1", - "babel-plugin-transform-es2015-classes": "6.24.1", - "babel-plugin-transform-es2015-computed-properties": "6.24.1", - "babel-plugin-transform-es2015-destructuring": "6.23.0", - "babel-plugin-transform-es2015-duplicate-keys": "6.24.1", - "babel-plugin-transform-es2015-for-of": "6.23.0", - "babel-plugin-transform-es2015-function-name": "6.24.1", - "babel-plugin-transform-es2015-literals": "6.22.0", - "babel-plugin-transform-es2015-modules-amd": "6.24.1", - "babel-plugin-transform-es2015-modules-commonjs": "6.24.1", - "babel-plugin-transform-es2015-modules-systemjs": "6.24.1", - "babel-plugin-transform-es2015-modules-umd": "6.24.1", - "babel-plugin-transform-es2015-object-super": "6.24.1", - "babel-plugin-transform-es2015-parameters": "6.24.1", - "babel-plugin-transform-es2015-shorthand-properties": "6.24.1", - "babel-plugin-transform-es2015-spread": "6.22.0", - "babel-plugin-transform-es2015-sticky-regex": "6.24.1", - "babel-plugin-transform-es2015-template-literals": "6.22.0", - "babel-plugin-transform-es2015-typeof-symbol": "6.23.0", - "babel-plugin-transform-es2015-unicode-regex": "6.24.1", - "babel-plugin-transform-exponentiation-operator": "6.24.1", - "babel-plugin-transform-regenerator": "6.24.1", - "browserslist": "1.7.7", - "invariant": "2.2.2" + "babel-plugin-check-es2015-constants": "^6.22.0", + "babel-plugin-syntax-trailing-function-commas": "^6.22.0", + "babel-plugin-transform-async-to-generator": "^6.22.0", + "babel-plugin-transform-es2015-arrow-functions": "^6.22.0", + "babel-plugin-transform-es2015-block-scoped-functions": "^6.22.0", + "babel-plugin-transform-es2015-block-scoping": "^6.23.0", + "babel-plugin-transform-es2015-classes": "^6.23.0", + "babel-plugin-transform-es2015-computed-properties": "^6.22.0", + "babel-plugin-transform-es2015-destructuring": "^6.23.0", + "babel-plugin-transform-es2015-duplicate-keys": "^6.22.0", + "babel-plugin-transform-es2015-for-of": "^6.23.0", + "babel-plugin-transform-es2015-function-name": "^6.22.0", + "babel-plugin-transform-es2015-literals": "^6.22.0", + "babel-plugin-transform-es2015-modules-amd": "^6.22.0", + "babel-plugin-transform-es2015-modules-commonjs": "^6.23.0", + "babel-plugin-transform-es2015-modules-systemjs": "^6.23.0", + "babel-plugin-transform-es2015-modules-umd": "^6.23.0", + "babel-plugin-transform-es2015-object-super": "^6.22.0", + "babel-plugin-transform-es2015-parameters": "^6.23.0", + "babel-plugin-transform-es2015-shorthand-properties": "^6.22.0", + "babel-plugin-transform-es2015-spread": "^6.22.0", + "babel-plugin-transform-es2015-sticky-regex": "^6.22.0", + "babel-plugin-transform-es2015-template-literals": "^6.22.0", + "babel-plugin-transform-es2015-typeof-symbol": "^6.23.0", + "babel-plugin-transform-es2015-unicode-regex": "^6.22.0", + "babel-plugin-transform-exponentiation-operator": "^6.22.0", + "babel-plugin-transform-regenerator": "^6.22.0", + "browserslist": "^1.4.0", + "invariant": "^2.2.2" } }, "babel-preset-flow": { @@ -869,7 +869,7 @@ "integrity": "sha1-5xIYiHCFrpoktb5Baa/7WZgWxJ0=", "dev": true, "requires": { - "babel-plugin-transform-flow-strip-types": "6.22.0" + "babel-plugin-transform-flow-strip-types": "^6.22.0" } }, "babel-preset-react": { @@ -878,12 +878,12 @@ "integrity": "sha1-umnfrqRfw+xjm2pOzqbhdwLJE4A=", "dev": true, "requires": { - "babel-plugin-syntax-jsx": "6.18.0", - "babel-plugin-transform-react-display-name": "6.23.0", - "babel-plugin-transform-react-jsx": "6.24.1", - "babel-plugin-transform-react-jsx-self": "6.22.0", - "babel-plugin-transform-react-jsx-source": "6.22.0", - "babel-preset-flow": "6.23.0" + "babel-plugin-syntax-jsx": "^6.3.13", + "babel-plugin-transform-react-display-name": "^6.23.0", + "babel-plugin-transform-react-jsx": "^6.24.1", + "babel-plugin-transform-react-jsx-self": "^6.22.0", + "babel-plugin-transform-react-jsx-source": "^6.22.0", + "babel-preset-flow": "^6.23.0" } }, "babel-register": { @@ -892,13 +892,13 @@ "integrity": "sha1-fhDhOi9xBlvfrVoXh7pFvKbe118=", "dev": true, "requires": { - "babel-core": "6.24.1", - "babel-runtime": "6.23.0", - "core-js": "2.4.1", - "home-or-tmp": "2.0.0", - "lodash": "4.17.4", - "mkdirp": "0.5.1", - "source-map-support": "0.4.14" + "babel-core": "^6.24.1", + "babel-runtime": "^6.22.0", + "core-js": "^2.4.0", + "home-or-tmp": "^2.0.0", + "lodash": "^4.2.0", + "mkdirp": "^0.5.1", + "source-map-support": "^0.4.2" }, "dependencies": { "core-js": { @@ -915,8 +915,8 @@ "integrity": "sha1-CpSJ8UTecO+zzkMArM2zKeL8VDs=", "dev": true, "requires": { - "core-js": "2.4.1", - "regenerator-runtime": "0.10.4" + "core-js": "^2.4.0", + "regenerator-runtime": "^0.10.0" }, "dependencies": { "core-js": { @@ -933,11 +933,11 @@ "integrity": "sha1-BK5RTx+Ts6JTfyoPYKWkX7gwgzM=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-traverse": "6.24.1", - "babel-types": "6.24.1", - "babylon": "6.17.0", - "lodash": "4.17.4" + "babel-runtime": "^6.22.0", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1", + "babylon": "^6.11.0", + "lodash": "^4.2.0" } }, "babel-traverse": { @@ -946,15 +946,15 @@ "integrity": "sha1-qzZnP9NW+aCUhlnnszjV/q2zFpU=", "dev": true, "requires": { - "babel-code-frame": "6.22.0", - "babel-messages": "6.23.0", - "babel-runtime": "6.23.0", - "babel-types": "6.24.1", - "babylon": "6.17.0", - "debug": "2.6.4", - "globals": "9.17.0", - "invariant": "2.2.2", - "lodash": "4.17.4" + "babel-code-frame": "^6.22.0", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1", + "babylon": "^6.15.0", + "debug": "^2.2.0", + "globals": "^9.0.0", + "invariant": "^2.2.0", + "lodash": "^4.2.0" } }, "babel-types": { @@ -963,10 +963,10 @@ "integrity": "sha1-oTaHncFbNga9oNkMH8dDBML/CXU=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "esutils": "2.0.2", - "lodash": "4.17.4", - "to-fast-properties": "1.0.2" + "babel-runtime": "^6.22.0", + "esutils": "^2.0.2", + "lodash": "^4.2.0", + "to-fast-properties": "^1.0.1" } }, "babylon": { @@ -1011,7 +1011,7 @@ "integrity": "sha1-Pv/DxQ4ABTH7cg6v+A8K6O8jz1k=", "dev": true, "requires": { - "balanced-match": "0.4.2", + "balanced-match": "^0.4.1", "concat-map": "0.0.1" } }, @@ -1021,9 +1021,9 @@ "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", "dev": true, "requires": { - "expand-range": "1.8.2", - "preserve": "0.2.0", - "repeat-element": "1.1.2" + "expand-range": "^1.8.1", + "preserve": "^0.2.0", + "repeat-element": "^1.1.2" } }, "brorand": { @@ -1038,11 +1038,11 @@ "integrity": "sha1-Xncl297x/Vkw1OurSFZ85FHEigo=", "dev": true, "requires": { - "buffer-xor": "1.0.3", - "cipher-base": "1.0.3", - "create-hash": "1.1.2", - "evp_bytestokey": "1.0.0", - "inherits": "2.0.3" + "buffer-xor": "^1.0.2", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "inherits": "^2.0.1" } }, "browserify-cipher": { @@ -1051,9 +1051,9 @@ "integrity": "sha1-mYgkSHS/XtTijalWZtzWasj8Njo=", "dev": true, "requires": { - "browserify-aes": "1.0.6", - "browserify-des": "1.0.0", - "evp_bytestokey": "1.0.0" + "browserify-aes": "^1.0.4", + "browserify-des": "^1.0.0", + "evp_bytestokey": "^1.0.0" } }, "browserify-des": { @@ -1062,9 +1062,9 @@ "integrity": "sha1-2qJ3cXRwki7S/hhZQRihdUOXId0=", "dev": true, "requires": { - "cipher-base": "1.0.3", - "des.js": "1.0.0", - "inherits": "2.0.3" + "cipher-base": "^1.0.1", + "des.js": "^1.0.0", + "inherits": "^2.0.1" } }, "browserify-rsa": { @@ -1073,8 +1073,8 @@ "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", "dev": true, "requires": { - "bn.js": "4.11.6", - "randombytes": "2.0.3" + "bn.js": "^4.1.0", + "randombytes": "^2.0.1" } }, "browserify-sign": { @@ -1083,13 +1083,13 @@ "integrity": "sha1-qk62jl17ZYuqa/alfmMMvXqT0pg=", "dev": true, "requires": { - "bn.js": "4.11.6", - "browserify-rsa": "4.0.1", - "create-hash": "1.1.2", - "create-hmac": "1.1.4", - "elliptic": "6.4.0", - "inherits": "2.0.3", - "parse-asn1": "5.1.0" + "bn.js": "^4.1.1", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.2", + "elliptic": "^6.0.0", + "inherits": "^2.0.1", + "parse-asn1": "^5.0.0" } }, "browserify-zlib": { @@ -1098,7 +1098,7 @@ "integrity": "sha1-uzX4pRn2AOD6a4SFJByXnQFB+y0=", "dev": true, "requires": { - "pako": "0.2.9" + "pako": "~0.2.0" } }, "browserslist": { @@ -1107,8 +1107,8 @@ "integrity": "sha1-C9dnBCWL6CmyOYu1Dkti0aFmsLk=", "dev": true, "requires": { - "caniuse-db": "1.0.30000662", - "electron-to-chromium": "1.3.8" + "caniuse-db": "^1.0.30000639", + "electron-to-chromium": "^1.2.7" } }, "buffer": { @@ -1117,9 +1117,9 @@ "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", "dev": true, "requires": { - "base64-js": "1.2.0", - "ieee754": "1.1.8", - "isarray": "1.0.0" + "base64-js": "^1.0.2", + "ieee754": "^1.1.4", + "isarray": "^1.0.0" } }, "buffer-shims": { @@ -1152,7 +1152,7 @@ "integrity": "sha1-lAhe9jWB7NPaqSREqP6U6CV3dR8=", "dev": true, "requires": { - "callsites": "0.2.0" + "callsites": "^0.2.0" } }, "callsites": { @@ -1173,10 +1173,10 @@ "integrity": "sha1-tTTnxzTE+B7F++isoq0kNUuWLGw=", "dev": true, "requires": { - "browserslist": "1.7.7", - "caniuse-db": "1.0.30000662", - "lodash.memoize": "4.1.2", - "lodash.uniq": "4.5.0" + "browserslist": "^1.3.6", + "caniuse-db": "^1.0.30000529", + "lodash.memoize": "^4.1.2", + "lodash.uniq": "^4.5.0" } }, "caniuse-db": { @@ -1191,8 +1191,8 @@ "integrity": "sha1-qg0yYptu6XIgBBHL1EYckHvCt60=", "dev": true, "requires": { - "align-text": "0.1.4", - "lazy-cache": "1.0.4" + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" } }, "chalk": { @@ -1201,11 +1201,11 @@ "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", "dev": true, "requires": { - "ansi-styles": "2.2.1", - "escape-string-regexp": "1.0.5", - "has-ansi": "2.0.0", - "strip-ansi": "3.0.1", - "supports-color": "2.0.0" + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" } }, "chokidar": { @@ -1214,15 +1214,15 @@ "integrity": "sha1-L0RHq16W5Q+z14n9kNTHLg5McMI=", "dev": true, "requires": { - "anymatch": "1.3.0", - "async-each": "1.0.1", - "fsevents": "1.1.1", - "glob-parent": "2.0.0", - "inherits": "2.0.3", - "is-binary-path": "1.0.1", - "is-glob": "2.0.1", - "path-is-absolute": "1.0.1", - "readdirp": "2.1.0" + "anymatch": "^1.3.0", + "async-each": "^1.0.0", + "fsevents": "^1.0.0", + "glob-parent": "^2.0.0", + "inherits": "^2.0.1", + "is-binary-path": "^1.0.0", + "is-glob": "^2.0.0", + "path-is-absolute": "^1.0.0", + "readdirp": "^2.0.0" } }, "cipher-base": { @@ -1231,7 +1231,7 @@ "integrity": "sha1-7qvxlEGc6QDaMBjCB9IS8qbfCgc=", "dev": true, "requires": { - "inherits": "2.0.3" + "inherits": "^2.0.1" } }, "circular-json": { @@ -1246,7 +1246,7 @@ "integrity": "sha1-s7026T3Uy/s5WjwmiWNSRFJlwFs=", "dev": true, "requires": { - "chalk": "1.1.3" + "chalk": "^1.1.3" } }, "cli-cursor": { @@ -1255,7 +1255,7 @@ "integrity": "sha1-ZNo/fValRBLll5S9Ytw1KV6PKYc=", "dev": true, "requires": { - "restore-cursor": "1.0.1" + "restore-cursor": "^1.0.1" } }, "cli-width": { @@ -1270,8 +1270,8 @@ "integrity": "sha1-S0dXYP+AJkx2LDoXGQMukcf+oNE=", "dev": true, "requires": { - "center-align": "0.1.3", - "right-align": "0.1.3", + "center-align": "^0.1.1", + "right-align": "^0.1.1", "wordwrap": "0.0.2" }, "dependencies": { @@ -1301,7 +1301,7 @@ "integrity": "sha1-f5WTRs/IcZ4/cjPNaFKFSnxn2KM=", "dev": true, "requires": { - "q": "1.5.0" + "q": "^1.1.2" } }, "code-point-at": { @@ -1316,9 +1316,9 @@ "integrity": "sha1-bXtcdPtl6EHNSHkq0e1eB7kE12Q=", "dev": true, "requires": { - "clone": "1.0.2", - "color-convert": "1.9.0", - "color-string": "0.3.0" + "clone": "^1.0.2", + "color-convert": "^1.3.0", + "color-string": "^0.3.0" } }, "color-convert": { @@ -1327,7 +1327,7 @@ "integrity": "sha1-Gsz5fdc5uYO/mU1W/sj5WFNkG3o=", "dev": true, "requires": { - "color-name": "1.1.2" + "color-name": "^1.1.1" } }, "color-name": { @@ -1342,7 +1342,7 @@ "integrity": "sha1-J9RvtnAlxcL6JZk7+/V55HhBuZE=", "dev": true, "requires": { - "color-name": "1.1.2" + "color-name": "^1.0.0" } }, "colormin": { @@ -1351,9 +1351,9 @@ "integrity": "sha1-6i90IKcrlogaOKrlnsEkpvcpgTM=", "dev": true, "requires": { - "color": "0.11.4", + "color": "^0.11.0", "css-color-names": "0.0.4", - "has": "1.0.1" + "has": "^1.0.1" } }, "colors": { @@ -1380,9 +1380,9 @@ "integrity": "sha1-CqxmL9Ur54lk1VMvaUeE5wEQrPc=", "dev": true, "requires": { - "inherits": "2.0.3", - "readable-stream": "2.2.9", - "typedarray": "0.0.6" + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" } }, "console-browserify": { @@ -1391,7 +1391,7 @@ "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", "dev": true, "requires": { - "date-now": "0.1.4" + "date-now": "^0.1.4" } }, "constants-browserify": { @@ -1429,8 +1429,8 @@ "integrity": "sha1-iIxyNZbN92EvZJgjPuvXo1MBc30=", "dev": true, "requires": { - "bn.js": "4.11.6", - "elliptic": "6.4.0" + "bn.js": "^4.1.0", + "elliptic": "^6.0.0" } }, "create-hash": { @@ -1439,10 +1439,10 @@ "integrity": "sha1-USEAYte7dHn2xlu0GpIgix1hq60=", "dev": true, "requires": { - "cipher-base": "1.0.3", - "inherits": "2.0.3", - "ripemd160": "1.0.1", - "sha.js": "2.4.8" + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "ripemd160": "^1.0.0", + "sha.js": "^2.3.6" } }, "create-hmac": { @@ -1451,8 +1451,8 @@ "integrity": "sha1-0/tLolPriz9W456i+8uK90e9MXA=", "dev": true, "requires": { - "create-hash": "1.1.2", - "inherits": "2.0.3" + "create-hash": "^1.1.0", + "inherits": "^2.0.1" } }, "crypto-browserify": { @@ -1461,16 +1461,16 @@ "integrity": "sha1-NlKgkGq5sqfgw85mpAjpV6JIVSI=", "dev": true, "requires": { - "browserify-cipher": "1.0.0", - "browserify-sign": "4.0.4", - "create-ecdh": "4.0.0", - "create-hash": "1.1.2", - "create-hmac": "1.1.4", - "diffie-hellman": "5.0.2", - "inherits": "2.0.3", - "pbkdf2": "3.0.9", - "public-encrypt": "4.0.0", - "randombytes": "2.0.3" + "browserify-cipher": "^1.0.0", + "browserify-sign": "^4.0.0", + "create-ecdh": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.0", + "diffie-hellman": "^5.0.0", + "inherits": "^2.0.1", + "pbkdf2": "^3.0.3", + "public-encrypt": "^4.0.0", + "randombytes": "^2.0.0" } }, "css-color-names": { @@ -1485,18 +1485,18 @@ "integrity": "sha1-th6eMNuUMD5v/IkvEOzQmtAlof0=", "dev": true, "requires": { - "babel-code-frame": "6.22.0", - "css-selector-tokenizer": "0.7.0", - "cssnano": "3.10.0", - "loader-utils": "1.1.0", - "lodash.camelcase": "4.3.0", - "object-assign": "4.1.1", - "postcss": "5.2.17", - "postcss-modules-extract-imports": "1.0.1", - "postcss-modules-local-by-default": "1.1.1", - "postcss-modules-scope": "1.0.2", - "postcss-modules-values": "1.2.2", - "source-list-map": "0.1.8" + "babel-code-frame": "^6.11.0", + "css-selector-tokenizer": "^0.7.0", + "cssnano": ">=2.6.1 <4", + "loader-utils": "^1.0.2", + "lodash.camelcase": "^4.3.0", + "object-assign": "^4.0.1", + "postcss": "^5.0.6", + "postcss-modules-extract-imports": "^1.0.0", + "postcss-modules-local-by-default": "^1.0.1", + "postcss-modules-scope": "^1.0.0", + "postcss-modules-values": "^1.1.0", + "source-list-map": "^0.1.7" }, "dependencies": { "loader-utils": { @@ -1505,9 +1505,9 @@ "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", "dev": true, "requires": { - "big.js": "3.1.3", - "emojis-list": "2.1.0", - "json5": "0.5.1" + "big.js": "^3.1.3", + "emojis-list": "^2.0.0", + "json5": "^0.5.0" } } } @@ -1518,9 +1518,9 @@ "integrity": "sha1-5piEdK6MlTR3v15+/s/OzNnPTIY=", "dev": true, "requires": { - "cssesc": "0.1.0", - "fastparse": "1.1.1", - "regexpu-core": "1.0.0" + "cssesc": "^0.1.0", + "fastparse": "^1.1.1", + "regexpu-core": "^1.0.0" }, "dependencies": { "regexpu-core": { @@ -1529,9 +1529,9 @@ "integrity": "sha1-hqdj9Y7k18L2sQLkdkBQ3n7ZDGs=", "dev": true, "requires": { - "regenerate": "1.3.2", - "regjsgen": "0.2.0", - "regjsparser": "0.1.5" + "regenerate": "^1.2.1", + "regjsgen": "^0.2.0", + "regjsparser": "^0.1.4" } } } @@ -1548,38 +1548,38 @@ "integrity": "sha1-Tzj2zqK5sX+gFJDyPx3GjqZcHDg=", "dev": true, "requires": { - "autoprefixer": "6.7.7", - "decamelize": "1.2.0", - "defined": "1.0.0", - "has": "1.0.1", - "object-assign": "4.1.1", - "postcss": "5.2.17", - "postcss-calc": "5.3.1", - "postcss-colormin": "2.2.2", - "postcss-convert-values": "2.6.1", - "postcss-discard-comments": "2.0.4", - "postcss-discard-duplicates": "2.1.0", - "postcss-discard-empty": "2.1.0", - "postcss-discard-overridden": "0.1.1", - "postcss-discard-unused": "2.2.3", - "postcss-filter-plugins": "2.0.2", - "postcss-merge-idents": "2.1.7", - "postcss-merge-longhand": "2.0.2", - "postcss-merge-rules": "2.1.2", - "postcss-minify-font-values": "1.0.5", - "postcss-minify-gradients": "1.0.5", - "postcss-minify-params": "1.2.2", - "postcss-minify-selectors": "2.1.1", - "postcss-normalize-charset": "1.1.1", - "postcss-normalize-url": "3.0.8", - "postcss-ordered-values": "2.2.3", - "postcss-reduce-idents": "2.4.0", - "postcss-reduce-initial": "1.0.1", - "postcss-reduce-transforms": "1.0.4", - "postcss-svgo": "2.1.6", - "postcss-unique-selectors": "2.0.2", - "postcss-value-parser": "3.3.0", - "postcss-zindex": "2.2.0" + "autoprefixer": "^6.3.1", + "decamelize": "^1.1.2", + "defined": "^1.0.0", + "has": "^1.0.1", + "object-assign": "^4.0.1", + "postcss": "^5.0.14", + "postcss-calc": "^5.2.0", + "postcss-colormin": "^2.1.8", + "postcss-convert-values": "^2.3.4", + "postcss-discard-comments": "^2.0.4", + "postcss-discard-duplicates": "^2.0.1", + "postcss-discard-empty": "^2.0.1", + "postcss-discard-overridden": "^0.1.1", + "postcss-discard-unused": "^2.2.1", + "postcss-filter-plugins": "^2.0.0", + "postcss-merge-idents": "^2.1.5", + "postcss-merge-longhand": "^2.0.1", + "postcss-merge-rules": "^2.0.3", + "postcss-minify-font-values": "^1.0.2", + "postcss-minify-gradients": "^1.0.1", + "postcss-minify-params": "^1.0.4", + "postcss-minify-selectors": "^2.0.4", + "postcss-normalize-charset": "^1.1.0", + "postcss-normalize-url": "^3.0.7", + "postcss-ordered-values": "^2.1.0", + "postcss-reduce-idents": "^2.2.2", + "postcss-reduce-initial": "^1.0.0", + "postcss-reduce-transforms": "^1.0.3", + "postcss-svgo": "^2.1.1", + "postcss-unique-selectors": "^2.0.2", + "postcss-value-parser": "^3.2.3", + "postcss-zindex": "^2.0.1" } }, "csso": { @@ -1588,8 +1588,8 @@ "integrity": "sha1-3dUsWHAz9J6Utx/FVWnyUuj/X4U=", "dev": true, "requires": { - "clap": "1.1.3", - "source-map": "0.5.6" + "clap": "^1.0.9", + "source-map": "^0.5.3" } }, "d": { @@ -1598,7 +1598,7 @@ "integrity": "sha1-dUu1v+VUUdpppYuU1F9MWwRi1Y8=", "dev": true, "requires": { - "es5-ext": "0.10.15" + "es5-ext": "^0.10.9" } }, "damerau-levenshtein": { @@ -1640,8 +1640,8 @@ "integrity": "sha1-g6c/L+pWmJj7c3GTyPhzyvbUXJQ=", "dev": true, "requires": { - "foreach": "2.0.5", - "object-keys": "1.0.11" + "foreach": "^2.0.5", + "object-keys": "^1.0.8" } }, "defined": { @@ -1656,13 +1656,13 @@ "integrity": "sha1-wSyYHQZ4RshLyvhiz/kw2Qf/0ag=", "dev": true, "requires": { - "globby": "5.0.0", - "is-path-cwd": "1.0.0", - "is-path-in-cwd": "1.0.0", - "object-assign": "4.1.1", - "pify": "2.3.0", - "pinkie-promise": "2.0.1", - "rimraf": "2.6.1" + "globby": "^5.0.0", + "is-path-cwd": "^1.0.0", + "is-path-in-cwd": "^1.0.0", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "rimraf": "^2.2.8" } }, "des.js": { @@ -1671,8 +1671,8 @@ "integrity": "sha1-wHTS4qpqipoH29YfmhXCzYPsjsw=", "dev": true, "requires": { - "inherits": "2.0.3", - "minimalistic-assert": "1.0.0" + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" } }, "detect-indent": { @@ -1681,7 +1681,7 @@ "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", "dev": true, "requires": { - "repeating": "2.0.1" + "repeating": "^2.0.0" } }, "diffie-hellman": { @@ -1690,9 +1690,9 @@ "integrity": "sha1-tYNXOScM/ias9jIJn97SoH8gnl4=", "dev": true, "requires": { - "bn.js": "4.11.6", - "miller-rabin": "4.0.0", - "randombytes": "2.0.3" + "bn.js": "^4.1.0", + "miller-rabin": "^4.0.0", + "randombytes": "^2.0.0" } }, "doctrine": { @@ -1701,8 +1701,8 @@ "integrity": "sha1-xz2NKQnSIpHhoAejlYBNqLZl/mM=", "dev": true, "requires": { - "esutils": "2.0.2", - "isarray": "1.0.0" + "esutils": "^2.0.2", + "isarray": "^1.0.0" } }, "domain-browser": { @@ -1716,9 +1716,9 @@ "resolved": "https://registry.npmjs.org/draft-js/-/draft-js-0.10.5.tgz", "integrity": "sha512-LE6jSCV9nkPhfVX2ggcRLA4FKs6zWq9ceuO/88BpXdNCS7mjRTgs0NsV6piUCJX9YxMsB9An33wnkMmU2sD2Zg==", "requires": { - "fbjs": "0.8.17", - "immutable": "3.7.6", - "object-assign": "4.1.1" + "fbjs": "^0.8.15", + "immutable": "~3.7.4", + "object-assign": "^4.1.0" }, "dependencies": { "immutable": { @@ -1740,13 +1740,13 @@ "integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=", "dev": true, "requires": { - "bn.js": "4.11.6", - "brorand": "1.1.0", - "hash.js": "1.0.3", - "hmac-drbg": "1.0.1", - "inherits": "2.0.3", - "minimalistic-assert": "1.0.0", - "minimalistic-crypto-utils": "1.0.1" + "bn.js": "^4.4.0", + "brorand": "^1.0.1", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" } }, "emojis-list": { @@ -1760,7 +1760,7 @@ "resolved": "http://registry.npmjs.org/encoding/-/encoding-0.1.12.tgz", "integrity": "sha1-U4tm8+5izRq1HsMjgp0flIDHS+s=", "requires": { - "iconv-lite": "0.4.16" + "iconv-lite": "~0.4.13" } }, "enhanced-resolve": { @@ -1769,10 +1769,10 @@ "integrity": "sha1-n0tib1dyRe3PSyrYPYbhf09CHew=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "memory-fs": "0.4.1", - "object-assign": "4.1.1", - "tapable": "0.2.6" + "graceful-fs": "^4.1.2", + "memory-fs": "^0.4.0", + "object-assign": "^4.0.1", + "tapable": "^0.2.5" } }, "errno": { @@ -1781,7 +1781,7 @@ "integrity": "sha1-uJbiOp5ei6M4cfyZar02NfyaHH0=", "dev": true, "requires": { - "prr": "0.0.0" + "prr": "~0.0.0" } }, "error-ex": { @@ -1790,7 +1790,7 @@ "integrity": "sha1-+FWobOYa3E6GIcPNoh56dhLDqNw=", "dev": true, "requires": { - "is-arrayish": "0.2.1" + "is-arrayish": "^0.2.1" } }, "es-abstract": { @@ -1799,10 +1799,10 @@ "integrity": "sha1-363ndOAb/Nl/lhgCmMRJyGI/uUw=", "dev": true, "requires": { - "es-to-primitive": "1.1.1", - "function-bind": "1.1.0", - "is-callable": "1.1.3", - "is-regex": "1.0.4" + "es-to-primitive": "^1.1.1", + "function-bind": "^1.1.0", + "is-callable": "^1.1.3", + "is-regex": "^1.0.3" } }, "es-to-primitive": { @@ -1811,9 +1811,9 @@ "integrity": "sha1-RTVSSKiJeQNLZ5Lhm7gfK3l13Q0=", "dev": true, "requires": { - "is-callable": "1.1.3", - "is-date-object": "1.0.1", - "is-symbol": "1.0.1" + "is-callable": "^1.1.1", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.1" } }, "es5-ext": { @@ -1822,8 +1822,8 @@ "integrity": "sha1-wzClk0we4hKEp8CBqG5f2TfJHqY=", "dev": true, "requires": { - "es6-iterator": "2.0.1", - "es6-symbol": "3.1.1" + "es6-iterator": "2", + "es6-symbol": "~3.1" } }, "es6-iterator": { @@ -1832,9 +1832,9 @@ "integrity": "sha1-jjGcnwRTv1ddN0lAplWSDlnKVRI=", "dev": true, "requires": { - "d": "1.0.0", - "es5-ext": "0.10.15", - "es6-symbol": "3.1.1" + "d": "1", + "es5-ext": "^0.10.14", + "es6-symbol": "^3.1" } }, "es6-map": { @@ -1843,12 +1843,12 @@ "integrity": "sha1-kTbgUD3MBqMBaQ8LsU/042TpSfA=", "dev": true, "requires": { - "d": "1.0.0", - "es5-ext": "0.10.15", - "es6-iterator": "2.0.1", - "es6-set": "0.1.5", - "es6-symbol": "3.1.1", - "event-emitter": "0.3.5" + "d": "1", + "es5-ext": "~0.10.14", + "es6-iterator": "~2.0.1", + "es6-set": "~0.1.5", + "es6-symbol": "~3.1.1", + "event-emitter": "~0.3.5" } }, "es6-set": { @@ -1857,11 +1857,11 @@ "integrity": "sha1-0rPsXU2ADO2BjbU40ol02wpzzLE=", "dev": true, "requires": { - "d": "1.0.0", - "es5-ext": "0.10.15", - "es6-iterator": "2.0.1", + "d": "1", + "es5-ext": "~0.10.14", + "es6-iterator": "~2.0.1", "es6-symbol": "3.1.1", - "event-emitter": "0.3.5" + "event-emitter": "~0.3.5" } }, "es6-symbol": { @@ -1870,8 +1870,8 @@ "integrity": "sha1-vwDvT9q2uhtG7Le2KbTH7VcVzHc=", "dev": true, "requires": { - "d": "1.0.0", - "es5-ext": "0.10.15" + "d": "1", + "es5-ext": "~0.10.14" } }, "es6-weak-map": { @@ -1880,10 +1880,10 @@ "integrity": "sha1-XjqzIlH/0VOKH45f+hNXdy+S2W8=", "dev": true, "requires": { - "d": "1.0.0", - "es5-ext": "0.10.15", - "es6-iterator": "2.0.1", - "es6-symbol": "3.1.1" + "d": "1", + "es5-ext": "^0.10.14", + "es6-iterator": "^2.0.1", + "es6-symbol": "^3.1.1" } }, "escape-string-regexp": { @@ -1898,10 +1898,10 @@ "integrity": "sha1-4Bl16BJ4GhY6ba392AOY3GTIicM=", "dev": true, "requires": { - "es6-map": "0.1.5", - "es6-weak-map": "2.0.2", - "esrecurse": "4.1.0", - "estraverse": "4.2.0" + "es6-map": "^0.1.3", + "es6-weak-map": "^2.0.1", + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" } }, "eslint": { @@ -1910,41 +1910,41 @@ "integrity": "sha1-yPxiAcf0DdCJQbh8CFdnOGpnmsw=", "dev": true, "requires": { - "babel-code-frame": "6.22.0", - "chalk": "1.1.3", - "concat-stream": "1.6.0", - "debug": "2.6.4", - "doctrine": "2.0.0", - "escope": "3.6.0", - "espree": "3.4.2", - "esquery": "1.0.0", - "estraverse": "4.2.0", - "esutils": "2.0.2", - "file-entry-cache": "2.0.0", - "glob": "7.1.1", - "globals": "9.17.0", - "ignore": "3.2.7", - "imurmurhash": "0.1.4", - "inquirer": "0.12.0", - "is-my-json-valid": "2.16.0", - "is-resolvable": "1.0.0", - "js-yaml": "3.7.0", - "json-stable-stringify": "1.0.1", - "levn": "0.3.0", - "lodash": "4.17.4", - "mkdirp": "0.5.1", - "natural-compare": "1.4.0", - "optionator": "0.8.2", - "path-is-inside": "1.0.2", - "pluralize": "1.2.1", - "progress": "1.1.8", - "require-uncached": "1.0.3", - "shelljs": "0.7.7", - "strip-bom": "3.0.0", - "strip-json-comments": "2.0.1", - "table": "3.8.3", - "text-table": "0.2.0", - "user-home": "2.0.0" + "babel-code-frame": "^6.16.0", + "chalk": "^1.1.3", + "concat-stream": "^1.5.2", + "debug": "^2.1.1", + "doctrine": "^2.0.0", + "escope": "^3.6.0", + "espree": "^3.4.0", + "esquery": "^1.0.0", + "estraverse": "^4.2.0", + "esutils": "^2.0.2", + "file-entry-cache": "^2.0.0", + "glob": "^7.0.3", + "globals": "^9.14.0", + "ignore": "^3.2.0", + "imurmurhash": "^0.1.4", + "inquirer": "^0.12.0", + "is-my-json-valid": "^2.10.0", + "is-resolvable": "^1.0.0", + "js-yaml": "^3.5.1", + "json-stable-stringify": "^1.0.0", + "levn": "^0.3.0", + "lodash": "^4.0.0", + "mkdirp": "^0.5.0", + "natural-compare": "^1.4.0", + "optionator": "^0.8.2", + "path-is-inside": "^1.0.1", + "pluralize": "^1.2.1", + "progress": "^1.1.8", + "require-uncached": "^1.0.2", + "shelljs": "^0.7.5", + "strip-bom": "^3.0.0", + "strip-json-comments": "~2.0.1", + "table": "^3.7.8", + "text-table": "~0.2.0", + "user-home": "^2.0.0" }, "dependencies": { "strip-bom": { @@ -1961,7 +1961,7 @@ "integrity": "sha1-NV0pAEC7+OAL+LSxn0twy+fCMX8=", "dev": true, "requires": { - "eslint-config-airbnb-base": "11.1.3" + "eslint-config-airbnb-base": "^11.1.0" } }, "eslint-config-airbnb-base": { @@ -1976,7 +1976,7 @@ "integrity": "sha1-TsX/s8CSz6Wh115+K6+QlmBRfrc=", "dev": true, "requires": { - "eslint-config-airbnb": "14.1.0" + "eslint-config-airbnb": "~14.1.0" } }, "eslint-import-resolver-node": { @@ -1985,9 +1985,9 @@ "integrity": "sha1-Wt2BBujJKNssuiMrzZ76hG49oWw=", "dev": true, "requires": { - "debug": "2.6.4", - "object-assign": "4.1.1", - "resolve": "1.3.3" + "debug": "^2.2.0", + "object-assign": "^4.0.1", + "resolve": "^1.1.6" } }, "eslint-module-utils": { @@ -1997,7 +1997,7 @@ "dev": true, "requires": { "debug": "2.2.0", - "pkg-dir": "1.0.0" + "pkg-dir": "^1.0.0" }, "dependencies": { "debug": { @@ -2023,16 +2023,16 @@ "integrity": "sha1-crowb60wXWfEgWNIpGmaQimsi04=", "dev": true, "requires": { - "builtin-modules": "1.1.1", - "contains-path": "0.1.0", - "debug": "2.6.4", + "builtin-modules": "^1.1.1", + "contains-path": "^0.1.0", + "debug": "^2.2.0", "doctrine": "1.5.0", - "eslint-import-resolver-node": "0.2.3", - "eslint-module-utils": "2.0.0", - "has": "1.0.1", - "lodash.cond": "4.5.2", - "minimatch": "3.0.3", - "pkg-up": "1.0.0" + "eslint-import-resolver-node": "^0.2.0", + "eslint-module-utils": "^2.0.0", + "has": "^1.0.1", + "lodash.cond": "^4.3.0", + "minimatch": "^3.0.3", + "pkg-up": "^1.0.0" }, "dependencies": { "doctrine": { @@ -2041,8 +2041,8 @@ "integrity": "sha1-N53Ocw9hZvds76TmcHoVmwLFpvo=", "dev": true, "requires": { - "esutils": "2.0.2", - "isarray": "1.0.0" + "esutils": "^2.0.2", + "isarray": "^1.0.0" } } } @@ -2053,9 +2053,9 @@ "integrity": "sha1-nw6ryv3j0qJgDZamatuQ0JnoQf4=", "dev": true, "requires": { - "damerau-levenshtein": "1.0.4", - "jsx-ast-utils": "1.4.1", - "object-assign": "4.1.1" + "damerau-levenshtein": "^1.0.0", + "jsx-ast-utils": "^1.0.0", + "object-assign": "^4.0.1" } }, "eslint-plugin-react": { @@ -2064,11 +2064,11 @@ "integrity": "sha1-xUNb6wZ3ThLH2y9qut3L+QDNP3g=", "dev": true, "requires": { - "array.prototype.find": "2.0.4", - "doctrine": "1.5.0", - "has": "1.0.1", - "jsx-ast-utils": "1.4.1", - "object.assign": "4.0.4" + "array.prototype.find": "^2.0.1", + "doctrine": "^1.2.2", + "has": "^1.0.1", + "jsx-ast-utils": "^1.3.4", + "object.assign": "^4.0.4" }, "dependencies": { "doctrine": { @@ -2077,8 +2077,8 @@ "integrity": "sha1-N53Ocw9hZvds76TmcHoVmwLFpvo=", "dev": true, "requires": { - "esutils": "2.0.2", - "isarray": "1.0.0" + "esutils": "^2.0.2", + "isarray": "^1.0.0" } } } @@ -2089,8 +2089,8 @@ "integrity": "sha1-ONve2+3JW4lhofvwRzSo9qnIxZI=", "dev": true, "requires": { - "acorn": "5.0.3", - "acorn-jsx": "3.0.1" + "acorn": "^5.0.1", + "acorn-jsx": "^3.0.0" } }, "esprima": { @@ -2105,7 +2105,7 @@ "integrity": "sha1-z7qLV9f7qT8XKYqKAGoEzaE9gPo=", "dev": true, "requires": { - "estraverse": "4.2.0" + "estraverse": "^4.0.0" } }, "esrecurse": { @@ -2114,8 +2114,8 @@ "integrity": "sha1-RxO2U2rffyrE8yfVWed1a/9kgiA=", "dev": true, "requires": { - "estraverse": "4.1.1", - "object-assign": "4.1.1" + "estraverse": "~4.1.0", + "object-assign": "^4.0.1" }, "dependencies": { "estraverse": { @@ -2144,8 +2144,8 @@ "integrity": "sha1-34xp7vFkeSPHFXuc6DhAYQsCzDk=", "dev": true, "requires": { - "d": "1.0.0", - "es5-ext": "0.10.15" + "d": "1", + "es5-ext": "~0.10.14" } }, "events": { @@ -2160,7 +2160,7 @@ "integrity": "sha1-SXtmrZ/vZc18CKYYCCS6FHa2blM=", "dev": true, "requires": { - "create-hash": "1.1.2" + "create-hash": "^1.1.1" } }, "exit-hook": { @@ -2175,7 +2175,7 @@ "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", "dev": true, "requires": { - "is-posix-bracket": "0.1.1" + "is-posix-bracket": "^0.1.0" } }, "expand-range": { @@ -2184,7 +2184,7 @@ "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=", "dev": true, "requires": { - "fill-range": "2.2.3" + "fill-range": "^2.1.0" } }, "extglob": { @@ -2193,7 +2193,7 @@ "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", "dev": true, "requires": { - "is-extglob": "1.0.0" + "is-extglob": "^1.0.0" } }, "extract-text-webpack-plugin": { @@ -2202,10 +2202,10 @@ "integrity": "sha1-aTFbiF+Hbb+W04Gfap8cynrr8Vk=", "dev": true, "requires": { - "ajv": "4.11.7", - "async": "2.3.0", - "loader-utils": "1.1.0", - "webpack-sources": "0.1.5" + "ajv": "^4.11.2", + "async": "^2.1.2", + "loader-utils": "^1.0.2", + "webpack-sources": "^0.1.0" }, "dependencies": { "loader-utils": { @@ -2214,9 +2214,9 @@ "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", "dev": true, "requires": { - "big.js": "3.1.3", - "emojis-list": "2.1.0", - "json5": "0.5.1" + "big.js": "^3.1.3", + "emojis-list": "^2.0.0", + "json5": "^0.5.0" } } } @@ -2238,13 +2238,13 @@ "resolved": "https://registry.npmjs.org/fbjs/-/fbjs-0.8.17.tgz", "integrity": "sha1-xNWY6taUkRJlPWWIsBpc3Nn5D90=", "requires": { - "core-js": "1.2.7", - "isomorphic-fetch": "2.2.1", - "loose-envify": "1.3.1", - "object-assign": "4.1.1", - "promise": "7.3.1", - "setimmediate": "1.0.5", - "ua-parser-js": "0.7.18" + "core-js": "^1.0.0", + "isomorphic-fetch": "^2.1.1", + "loose-envify": "^1.0.0", + "object-assign": "^4.1.0", + "promise": "^7.1.1", + "setimmediate": "^1.0.5", + "ua-parser-js": "^0.7.18" }, "dependencies": { "promise": { @@ -2252,7 +2252,7 @@ "resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz", "integrity": "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg==", "requires": { - "asap": "2.0.6" + "asap": "~2.0.3" } } } @@ -2263,8 +2263,8 @@ "integrity": "sha1-y+Hjr/zxzUS4DK3+0o3Hk6lwHS4=", "dev": true, "requires": { - "escape-string-regexp": "1.0.5", - "object-assign": "4.1.1" + "escape-string-regexp": "^1.0.5", + "object-assign": "^4.1.0" } }, "file-entry-cache": { @@ -2273,8 +2273,8 @@ "integrity": "sha1-w5KZDD5oR4PYOLjISkXYoEhFg2E=", "dev": true, "requires": { - "flat-cache": "1.2.2", - "object-assign": "4.1.1" + "flat-cache": "^1.2.1", + "object-assign": "^4.0.1" } }, "filename-regex": { @@ -2289,11 +2289,11 @@ "integrity": "sha1-ULd9/X5Gm8dJJHCWNpn+eoSFpyM=", "dev": true, "requires": { - "is-number": "2.1.0", - "isobject": "2.1.0", - "randomatic": "1.1.6", - "repeat-element": "1.1.2", - "repeat-string": "1.6.1" + "is-number": "^2.1.0", + "isobject": "^2.0.0", + "randomatic": "^1.1.3", + "repeat-element": "^1.1.2", + "repeat-string": "^1.5.2" } }, "find-cache-dir": { @@ -2302,9 +2302,9 @@ "integrity": "sha1-yN765XyKUqinhPnjHFfHQumToLk=", "dev": true, "requires": { - "commondir": "1.0.1", - "mkdirp": "0.5.1", - "pkg-dir": "1.0.0" + "commondir": "^1.0.1", + "mkdirp": "^0.5.1", + "pkg-dir": "^1.0.0" } }, "flat-cache": { @@ -2313,10 +2313,10 @@ "integrity": "sha1-+oZxTnLCHbiGAXYezy9VXRq8a5Y=", "dev": true, "requires": { - "circular-json": "0.3.1", - "del": "2.2.2", - "graceful-fs": "4.1.11", - "write": "0.2.1" + "circular-json": "^0.3.1", + "del": "^2.0.2", + "graceful-fs": "^4.1.2", + "write": "^0.2.1" } }, "flatten": { @@ -2337,7 +2337,7 @@ "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", "dev": true, "requires": { - "for-in": "1.0.2" + "for-in": "^1.0.1" } }, "foreach": { @@ -2359,8 +2359,8 @@ "dev": true, "optional": true, "requires": { - "nan": "2.6.2", - "node-pre-gyp": "0.6.33" + "nan": "^2.3.0", + "node-pre-gyp": "^0.6.29" }, "dependencies": { "abbrev": { @@ -2457,6 +2457,7 @@ "resolved": "https://registry.npmjs.org/block-stream/-/block-stream-0.0.9.tgz", "integrity": "sha1-E+v+d4oDIFz+A3UUgeu0szAMEmo=", "dev": true, + "optional": true, "requires": { "inherits": "2.0.3" } @@ -2466,6 +2467,7 @@ "resolved": "https://registry.npmjs.org/boom/-/boom-2.10.1.tgz", "integrity": "sha1-OciRjO/1eZ+D+UkqhI9iWt0Mdm8=", "dev": true, + "optional": true, "requires": { "hoek": "2.16.3" } @@ -2484,7 +2486,8 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/buffer-shims/-/buffer-shims-1.0.0.tgz", "integrity": "sha1-mXjOMXOIxkmth5MCjDR37wRKi1E=", - "dev": true + "dev": true, + "optional": true }, "caseless": { "version": "0.11.0", @@ -2511,13 +2514,15 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", - "dev": true + "dev": true, + "optional": true }, "combined-stream": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.5.tgz", "integrity": "sha1-k4NwpXtKUd6ix3wV1cX9+JUWQAk=", "dev": true, + "optional": true, "requires": { "delayed-stream": "1.0.0" } @@ -2542,13 +2547,15 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", - "dev": true + "dev": true, + "optional": true }, "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", - "dev": true + "dev": true, + "optional": true }, "cryptiles": { "version": "2.0.5", @@ -2600,7 +2607,8 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", - "dev": true + "dev": true, + "optional": true }, "delegates": { "version": "1.0.0", @@ -2637,7 +2645,8 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.0.2.tgz", "integrity": "sha1-4QgOBljjALBilJkMxw4VAiNf1VA=", - "dev": true + "dev": true, + "optional": true }, "forever-agent": { "version": "0.6.1", @@ -2857,6 +2866,7 @@ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", "dev": true, + "optional": true, "requires": { "number-is-nan": "1.0.1" } @@ -2892,7 +2902,8 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", - "dev": true + "dev": true, + "optional": true }, "isstream": { "version": "0.1.2", @@ -2955,13 +2966,15 @@ "version": "1.26.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.26.0.tgz", "integrity": "sha1-6v/NDk/Gk1z4E02iRuLmw1MFrf8=", - "dev": true + "dev": true, + "optional": true }, "mime-types": { "version": "2.1.14", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.14.tgz", "integrity": "sha1-9+99l1g/yvO30oK2+LVnnaselO4=", "dev": true, + "optional": true, "requires": { "mime-db": "1.26.0" } @@ -3042,7 +3055,8 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", - "dev": true + "dev": true, + "optional": true }, "oauth-sign": { "version": "0.8.2", @@ -3094,7 +3108,8 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=", - "dev": true + "dev": true, + "optional": true }, "punycode": { "version": "1.4.1", @@ -3249,6 +3264,7 @@ "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", "dev": true, + "optional": true, "requires": { "code-point-at": "1.1.0", "is-fullwidth-code-point": "1.0.0", @@ -3259,7 +3275,8 @@ "version": "0.10.31", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "dev": true + "dev": true, + "optional": true }, "stringstream": { "version": "0.0.5", @@ -3296,6 +3313,7 @@ "resolved": "https://registry.npmjs.org/tar/-/tar-2.2.1.tgz", "integrity": "sha1-jk0qJWwOIYXGsYrWlK7JaLg8sdE=", "dev": true, + "optional": true, "requires": { "block-stream": "0.0.9", "fstream": "1.0.10", @@ -3382,7 +3400,8 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", - "dev": true + "dev": true, + "optional": true }, "uuid": { "version": "3.0.1", @@ -3444,7 +3463,7 @@ "integrity": "sha1-nA4cQDCM6AT0eDYYuTf6iPmdUNA=", "dev": true, "requires": { - "is-property": "1.0.2" + "is-property": "^1.0.0" } }, "get-caller-file": { @@ -3459,12 +3478,12 @@ "integrity": "sha1-gFIR3wT6rxxjo2ADBs31reULLsg=", "dev": true, "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.3", - "once": "1.4.0", - "path-is-absolute": "1.0.1" + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.2", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" } }, "glob-base": { @@ -3473,8 +3492,8 @@ "integrity": "sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=", "dev": true, "requires": { - "glob-parent": "2.0.0", - "is-glob": "2.0.1" + "glob-parent": "^2.0.0", + "is-glob": "^2.0.0" } }, "glob-parent": { @@ -3483,7 +3502,7 @@ "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", "dev": true, "requires": { - "is-glob": "2.0.1" + "is-glob": "^2.0.0" } }, "globals": { @@ -3498,12 +3517,12 @@ "integrity": "sha1-69hGZ8oNuzMLmbz8aOrCvFQ3Dg0=", "dev": true, "requires": { - "array-union": "1.0.2", - "arrify": "1.0.1", - "glob": "7.1.1", - "object-assign": "4.1.1", - "pify": "2.3.0", - "pinkie-promise": "2.0.1" + "array-union": "^1.0.1", + "arrify": "^1.0.0", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" } }, "graceful-fs": { @@ -3518,7 +3537,7 @@ "integrity": "sha1-hGFzP1OLCDfJNh45qauelwTcLyg=", "dev": true, "requires": { - "function-bind": "1.1.0" + "function-bind": "^1.0.2" } }, "has-ansi": { @@ -3527,7 +3546,7 @@ "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", "dev": true, "requires": { - "ansi-regex": "2.1.1" + "ansi-regex": "^2.0.0" } }, "has-flag": { @@ -3542,7 +3561,7 @@ "integrity": "sha1-EzL/ABVsCg/92CNgE9B7d6BFFXM=", "dev": true, "requires": { - "inherits": "2.0.3" + "inherits": "^2.0.1" } }, "hmac-drbg": { @@ -3551,9 +3570,9 @@ "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", "dev": true, "requires": { - "hash.js": "1.0.3", - "minimalistic-assert": "1.0.0", - "minimalistic-crypto-utils": "1.0.1" + "hash.js": "^1.0.3", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.1" } }, "home-or-tmp": { @@ -3562,8 +3581,8 @@ "integrity": "sha1-42w/LSyufXRqhX440Y1fMqeILbg=", "dev": true, "requires": { - "os-homedir": "1.0.2", - "os-tmpdir": "1.0.2" + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.1" } }, "hosted-git-info": { @@ -3631,8 +3650,8 @@ "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", "dev": true, "requires": { - "once": "1.4.0", - "wrappy": "1.0.2" + "once": "^1.3.0", + "wrappy": "1" } }, "inherits": { @@ -3647,19 +3666,19 @@ "integrity": "sha1-HvK/1jUE3wvHV4X/+MLEHfEvB34=", "dev": true, "requires": { - "ansi-escapes": "1.4.0", - "ansi-regex": "2.1.1", - "chalk": "1.1.3", - "cli-cursor": "1.0.2", - "cli-width": "2.1.0", - "figures": "1.7.0", - "lodash": "4.17.4", - "readline2": "1.0.1", - "run-async": "0.1.0", - "rx-lite": "3.1.2", - "string-width": "1.0.2", - "strip-ansi": "3.0.1", - "through": "2.3.8" + "ansi-escapes": "^1.1.0", + "ansi-regex": "^2.0.0", + "chalk": "^1.0.0", + "cli-cursor": "^1.0.1", + "cli-width": "^2.0.0", + "figures": "^1.3.5", + "lodash": "^4.3.0", + "readline2": "^1.0.1", + "run-async": "^0.1.0", + "rx-lite": "^3.1.2", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.0", + "through": "^2.3.6" } }, "interpret": { @@ -3674,7 +3693,7 @@ "integrity": "sha1-nh9WrArNtr8wMwbzOL47IErmA2A=", "dev": true, "requires": { - "loose-envify": "1.3.1" + "loose-envify": "^1.0.0" } }, "invert-kv": { @@ -3701,7 +3720,7 @@ "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", "dev": true, "requires": { - "binary-extensions": "1.8.0" + "binary-extensions": "^1.0.0" } }, "is-buffer": { @@ -3716,7 +3735,7 @@ "integrity": "sha1-VAVy0096wxGfj3bDDLwbHgN6/74=", "dev": true, "requires": { - "builtin-modules": "1.1.1" + "builtin-modules": "^1.0.0" } }, "is-callable": { @@ -3743,7 +3762,7 @@ "integrity": "sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=", "dev": true, "requires": { - "is-primitive": "2.0.0" + "is-primitive": "^2.0.0" } }, "is-extendable": { @@ -3764,7 +3783,7 @@ "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", "dev": true, "requires": { - "number-is-nan": "1.0.1" + "number-is-nan": "^1.0.0" } }, "is-fullwidth-code-point": { @@ -3773,7 +3792,7 @@ "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", "dev": true, "requires": { - "number-is-nan": "1.0.1" + "number-is-nan": "^1.0.0" } }, "is-glob": { @@ -3782,7 +3801,7 @@ "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", "dev": true, "requires": { - "is-extglob": "1.0.0" + "is-extglob": "^1.0.0" } }, "is-my-json-valid": { @@ -3791,10 +3810,10 @@ "integrity": "sha1-8Hndm/2uZe4gOKrorLyGqxCeNpM=", "dev": true, "requires": { - "generate-function": "2.0.0", - "generate-object-property": "1.2.0", - "jsonpointer": "4.0.1", - "xtend": "4.0.1" + "generate-function": "^2.0.0", + "generate-object-property": "^1.1.0", + "jsonpointer": "^4.0.0", + "xtend": "^4.0.0" } }, "is-number": { @@ -3803,7 +3822,7 @@ "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", "dev": true, "requires": { - "kind-of": "3.2.0" + "kind-of": "^3.0.2" } }, "is-path-cwd": { @@ -3818,7 +3837,7 @@ "integrity": "sha1-ZHdYK4IU1gI0YJRWcAO+ip6sBNw=", "dev": true, "requires": { - "is-path-inside": "1.0.0" + "is-path-inside": "^1.0.0" } }, "is-path-inside": { @@ -3827,7 +3846,7 @@ "integrity": "sha1-/AbloWg/vaE95mev9xe7wQpI838=", "dev": true, "requires": { - "path-is-inside": "1.0.2" + "path-is-inside": "^1.0.1" } }, "is-plain-obj": { @@ -3860,7 +3879,7 @@ "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", "dev": true, "requires": { - "has": "1.0.1" + "has": "^1.0.1" } }, "is-resolvable": { @@ -3869,7 +3888,7 @@ "integrity": "sha1-jfV8YeouPFAUCNEA+wE8+NbgzGI=", "dev": true, "requires": { - "tryit": "1.0.3" + "tryit": "^1.0.1" } }, "is-stream": { @@ -3883,7 +3902,7 @@ "integrity": "sha1-z2EJDaDZ77yrhyLeum8DIgjbsOk=", "dev": true, "requires": { - "html-comment-regex": "1.1.1" + "html-comment-regex": "^1.1.0" } }, "is-symbol": { @@ -3918,8 +3937,8 @@ "resolved": "http://registry.npmjs.org/isomorphic-fetch/-/isomorphic-fetch-2.2.1.tgz", "integrity": "sha1-YRrhrPFPXoH3KVB0coGf6XM1WKk=", "requires": { - "node-fetch": "1.6.3", - "whatwg-fetch": "2.0.3" + "node-fetch": "^1.0.1", + "whatwg-fetch": ">=0.10.0" } }, "js-base64": { @@ -3939,8 +3958,8 @@ "integrity": "sha1-XJZ93YN6m/3KXy3oQlOr6KHAO4A=", "dev": true, "requires": { - "argparse": "1.0.9", - "esprima": "2.7.3" + "argparse": "^1.0.7", + "esprima": "^2.6.0" } }, "jsesc": { @@ -3961,7 +3980,7 @@ "integrity": "sha1-mnWdOcXy/1A/1TAGRu1EX4jE+a8=", "dev": true, "requires": { - "jsonify": "0.0.0" + "jsonify": "~0.0.0" } }, "json5": { @@ -3994,7 +4013,7 @@ "integrity": "sha1-tYq+TVwEStM3JqjBUltIz4kb/wc=", "dev": true, "requires": { - "is-buffer": "1.1.5" + "is-buffer": "^1.1.5" } }, "lazy-cache": { @@ -4009,7 +4028,7 @@ "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", "dev": true, "requires": { - "invert-kv": "1.0.0" + "invert-kv": "^1.0.0" } }, "levn": { @@ -4018,8 +4037,8 @@ "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", "dev": true, "requires": { - "prelude-ls": "1.1.2", - "type-check": "0.3.2" + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" } }, "load-json-file": { @@ -4028,11 +4047,11 @@ "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "parse-json": "2.2.0", - "pify": "2.3.0", - "pinkie-promise": "2.0.1", - "strip-bom": "2.0.0" + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "strip-bom": "^2.0.0" } }, "loader-runner": { @@ -4047,10 +4066,10 @@ "integrity": "sha1-+G5jdNQyBabmxg6RlvF8Apm/s0g=", "dev": true, "requires": { - "big.js": "3.1.3", - "emojis-list": "2.1.0", - "json5": "0.5.1", - "object-assign": "4.1.1" + "big.js": "^3.1.3", + "emojis-list": "^2.0.0", + "json5": "^0.5.0", + "object-assign": "^4.0.1" } }, "lodash": { @@ -4094,7 +4113,7 @@ "resolved": "http://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", "requires": { - "js-tokens": "3.0.1" + "js-tokens": "^3.0.0" } }, "macaddress": { @@ -4115,8 +4134,8 @@ "integrity": "sha1-OpoguEYlI+RHz7x+i7gO1me/xVI=", "dev": true, "requires": { - "errno": "0.1.4", - "readable-stream": "2.2.9" + "errno": "^0.1.3", + "readable-stream": "^2.0.1" } }, "micromatch": { @@ -4125,19 +4144,19 @@ "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", "dev": true, "requires": { - "arr-diff": "2.0.0", - "array-unique": "0.2.1", - "braces": "1.8.5", - "expand-brackets": "0.1.5", - "extglob": "0.3.2", - "filename-regex": "2.0.0", - "is-extglob": "1.0.0", - "is-glob": "2.0.1", - "kind-of": "3.2.0", - "normalize-path": "2.1.1", - "object.omit": "2.0.1", - "parse-glob": "3.0.4", - "regex-cache": "0.4.3" + "arr-diff": "^2.0.0", + "array-unique": "^0.2.1", + "braces": "^1.8.2", + "expand-brackets": "^0.1.4", + "extglob": "^0.3.1", + "filename-regex": "^2.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.1", + "kind-of": "^3.0.2", + "normalize-path": "^2.0.1", + "object.omit": "^2.0.0", + "parse-glob": "^3.0.4", + "regex-cache": "^0.4.2" } }, "miller-rabin": { @@ -4146,8 +4165,8 @@ "integrity": "sha1-SmL7HUKTPAVYOYL0xxb2+55sbT0=", "dev": true, "requires": { - "bn.js": "4.11.6", - "brorand": "1.1.0" + "bn.js": "^4.0.0", + "brorand": "^1.0.1" } }, "minimalistic-assert": { @@ -4168,7 +4187,7 @@ "integrity": "sha1-Kk5AkLlrLbBqnX3wEFWmKnfJt3Q=", "dev": true, "requires": { - "brace-expansion": "1.1.7" + "brace-expansion": "^1.0.0" } }, "minimist": { @@ -4216,8 +4235,8 @@ "resolved": "http://registry.npmjs.org/node-fetch/-/node-fetch-1.6.3.tgz", "integrity": "sha1-3CNO3WSJmC1Y6PDbT2lQKavNjAQ=", "requires": { - "encoding": "0.1.12", - "is-stream": "1.1.0" + "encoding": "^0.1.11", + "is-stream": "^1.0.1" } }, "node-libs-browser": { @@ -4226,28 +4245,28 @@ "integrity": "sha1-o6WeyXAkmFtG6Vg3lkb5bEthZkY=", "dev": true, "requires": { - "assert": "1.4.1", - "browserify-zlib": "0.1.4", - "buffer": "4.9.1", - "console-browserify": "1.1.0", - "constants-browserify": "1.0.0", - "crypto-browserify": "3.11.0", - "domain-browser": "1.1.7", - "events": "1.1.1", + "assert": "^1.1.1", + "browserify-zlib": "^0.1.4", + "buffer": "^4.3.0", + "console-browserify": "^1.1.0", + "constants-browserify": "^1.0.0", + "crypto-browserify": "^3.11.0", + "domain-browser": "^1.1.1", + "events": "^1.0.0", "https-browserify": "0.0.1", - "os-browserify": "0.2.1", + "os-browserify": "^0.2.0", "path-browserify": "0.0.0", - "process": "0.11.10", - "punycode": "1.4.1", - "querystring-es3": "0.2.1", - "readable-stream": "2.2.9", - "stream-browserify": "2.0.1", - "stream-http": "2.7.0", - "string_decoder": "0.10.31", - "timers-browserify": "2.0.2", + "process": "^0.11.0", + "punycode": "^1.2.4", + "querystring-es3": "^0.2.0", + "readable-stream": "^2.0.5", + "stream-browserify": "^2.0.1", + "stream-http": "^2.3.1", + "string_decoder": "^0.10.25", + "timers-browserify": "^2.0.2", "tty-browserify": "0.0.0", - "url": "0.11.0", - "util": "0.10.3", + "url": "^0.11.0", + "util": "^0.10.3", "vm-browserify": "0.0.4" }, "dependencies": { @@ -4265,10 +4284,10 @@ "integrity": "sha1-2Bntoqne29H/pWPqQHHZNngilbs=", "dev": true, "requires": { - "hosted-git-info": "2.4.2", - "is-builtin-module": "1.0.0", - "semver": "5.3.0", - "validate-npm-package-license": "3.0.1" + "hosted-git-info": "^2.1.4", + "is-builtin-module": "^1.0.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" } }, "normalize-path": { @@ -4277,7 +4296,7 @@ "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", "dev": true, "requires": { - "remove-trailing-separator": "1.0.1" + "remove-trailing-separator": "^1.0.1" } }, "normalize-range": { @@ -4292,10 +4311,10 @@ "integrity": "sha1-LMDWazHqIwNkWENuNiDYWVTGbDw=", "dev": true, "requires": { - "object-assign": "4.1.1", - "prepend-http": "1.0.4", - "query-string": "4.3.4", - "sort-keys": "1.1.2" + "object-assign": "^4.0.1", + "prepend-http": "^1.0.0", + "query-string": "^4.1.0", + "sort-keys": "^1.0.0" } }, "num2fraction": { @@ -4327,9 +4346,9 @@ "integrity": "sha1-scnMBE7xuf5jYG/BQau7MuFHMMw=", "dev": true, "requires": { - "define-properties": "1.1.2", - "function-bind": "1.1.0", - "object-keys": "1.0.11" + "define-properties": "^1.1.2", + "function-bind": "^1.1.0", + "object-keys": "^1.0.10" } }, "object.omit": { @@ -4338,8 +4357,8 @@ "integrity": "sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=", "dev": true, "requires": { - "for-own": "0.1.5", - "is-extendable": "0.1.1" + "for-own": "^0.1.4", + "is-extendable": "^0.1.1" } }, "once": { @@ -4348,7 +4367,7 @@ "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "dev": true, "requires": { - "wrappy": "1.0.2" + "wrappy": "1" } }, "onetime": { @@ -4363,12 +4382,12 @@ "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", "dev": true, "requires": { - "deep-is": "0.1.3", - "fast-levenshtein": "2.0.6", - "levn": "0.3.0", - "prelude-ls": "1.1.2", - "type-check": "0.3.2", - "wordwrap": "1.0.0" + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.4", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "wordwrap": "~1.0.0" } }, "os-browserify": { @@ -4389,7 +4408,7 @@ "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", "dev": true, "requires": { - "lcid": "1.0.0" + "lcid": "^1.0.0" } }, "os-tmpdir": { @@ -4410,11 +4429,11 @@ "integrity": "sha1-N8T5t+06tlx0gXtfJICTf7+XxxI=", "dev": true, "requires": { - "asn1.js": "4.9.1", - "browserify-aes": "1.0.6", - "create-hash": "1.1.2", - "evp_bytestokey": "1.0.0", - "pbkdf2": "3.0.9" + "asn1.js": "^4.0.0", + "browserify-aes": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "pbkdf2": "^3.0.3" } }, "parse-glob": { @@ -4423,10 +4442,10 @@ "integrity": "sha1-ssN2z7EfNVE7rdFz7wu246OIORw=", "dev": true, "requires": { - "glob-base": "0.3.0", - "is-dotfile": "1.0.2", - "is-extglob": "1.0.0", - "is-glob": "2.0.1" + "glob-base": "^0.3.0", + "is-dotfile": "^1.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.0" } }, "parse-json": { @@ -4435,7 +4454,7 @@ "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", "dev": true, "requires": { - "error-ex": "1.3.1" + "error-ex": "^1.2.0" } }, "path-browserify": { @@ -4468,9 +4487,9 @@ "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "pify": "2.3.0", - "pinkie-promise": "2.0.1" + "graceful-fs": "^4.1.2", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" } }, "pbkdf2": { @@ -4479,7 +4498,7 @@ "integrity": "sha1-8sSyWmAAWLPDdzwIbDfbvuH/5pM=", "dev": true, "requires": { - "create-hmac": "1.1.4" + "create-hmac": "^1.1.2" } }, "pify": { @@ -4500,7 +4519,7 @@ "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", "dev": true, "requires": { - "pinkie": "2.0.4" + "pinkie": "^2.0.0" } }, "pkg-dir": { @@ -4509,7 +4528,7 @@ "integrity": "sha1-ektQio1bstYp1EcFb/TpyTFM89Q=", "dev": true, "requires": { - "find-up": "1.1.2" + "find-up": "^1.0.0" }, "dependencies": { "find-up": { @@ -4518,8 +4537,8 @@ "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", "dev": true, "requires": { - "path-exists": "2.1.0", - "pinkie-promise": "2.0.1" + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" } }, "path-exists": { @@ -4528,7 +4547,7 @@ "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", "dev": true, "requires": { - "pinkie-promise": "2.0.1" + "pinkie-promise": "^2.0.0" } } } @@ -4539,7 +4558,7 @@ "integrity": "sha1-Pgj7RhUlxEIWJKM7n35tCvWwWiY=", "dev": true, "requires": { - "find-up": "1.1.2" + "find-up": "^1.0.0" }, "dependencies": { "find-up": { @@ -4548,8 +4567,8 @@ "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", "dev": true, "requires": { - "path-exists": "2.1.0", - "pinkie-promise": "2.0.1" + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" } }, "path-exists": { @@ -4558,7 +4577,7 @@ "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", "dev": true, "requires": { - "pinkie-promise": "2.0.1" + "pinkie-promise": "^2.0.0" } } } @@ -4575,10 +4594,10 @@ "integrity": "sha1-z09Ze4ZNZcikkrLqvp1wbIecOIs=", "dev": true, "requires": { - "chalk": "1.1.3", - "js-base64": "2.1.9", - "source-map": "0.5.6", - "supports-color": "3.2.3" + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" }, "dependencies": { "supports-color": { @@ -4587,7 +4606,7 @@ "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", "dev": true, "requires": { - "has-flag": "1.0.0" + "has-flag": "^1.0.0" } } } @@ -4598,9 +4617,9 @@ "integrity": "sha1-d7rnypKK2FcW4v2kLyYb98HWW14=", "dev": true, "requires": { - "postcss": "5.2.17", - "postcss-message-helpers": "2.0.0", - "reduce-css-calc": "1.3.0" + "postcss": "^5.0.2", + "postcss-message-helpers": "^2.0.0", + "reduce-css-calc": "^1.2.6" } }, "postcss-colormin": { @@ -4609,9 +4628,9 @@ "integrity": "sha1-ZjFBfV8OkJo9fsJrJMio0eT5bks=", "dev": true, "requires": { - "colormin": "1.1.2", - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0" + "colormin": "^1.0.5", + "postcss": "^5.0.13", + "postcss-value-parser": "^3.2.3" } }, "postcss-convert-values": { @@ -4620,8 +4639,8 @@ "integrity": "sha1-u9hZPFwf0uPRwyK7kl3K6Nrk1i0=", "dev": true, "requires": { - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0" + "postcss": "^5.0.11", + "postcss-value-parser": "^3.1.2" } }, "postcss-discard-comments": { @@ -4630,7 +4649,7 @@ "integrity": "sha1-vv6J+v1bPazlzM5Rt2uBUUvgDj0=", "dev": true, "requires": { - "postcss": "5.2.17" + "postcss": "^5.0.14" } }, "postcss-discard-duplicates": { @@ -4639,7 +4658,7 @@ "integrity": "sha1-uavye4isGIFYpesSq8riAmO5GTI=", "dev": true, "requires": { - "postcss": "5.2.17" + "postcss": "^5.0.4" } }, "postcss-discard-empty": { @@ -4648,7 +4667,7 @@ "integrity": "sha1-0rS9nVztXr2Nyt52QMfXzX9PkrU=", "dev": true, "requires": { - "postcss": "5.2.17" + "postcss": "^5.0.14" } }, "postcss-discard-overridden": { @@ -4657,7 +4676,7 @@ "integrity": "sha1-ix6vVU9ob7KIzYdMVWZ7CqNmjVg=", "dev": true, "requires": { - "postcss": "5.2.17" + "postcss": "^5.0.16" } }, "postcss-discard-unused": { @@ -4666,8 +4685,8 @@ "integrity": "sha1-vOMLLMWR/8Y0Mitfs0ZLbZNPRDM=", "dev": true, "requires": { - "postcss": "5.2.17", - "uniqs": "2.0.0" + "postcss": "^5.0.14", + "uniqs": "^2.0.0" } }, "postcss-filter-plugins": { @@ -4676,8 +4695,8 @@ "integrity": "sha1-bYWGJTTXNaxCDkqFgG4fXUKG2Ew=", "dev": true, "requires": { - "postcss": "5.2.17", - "uniqid": "4.1.1" + "postcss": "^5.0.4", + "uniqid": "^4.0.0" } }, "postcss-merge-idents": { @@ -4686,9 +4705,9 @@ "integrity": "sha1-TFUwMTwI4dWzu/PSu8dH4njuonA=", "dev": true, "requires": { - "has": "1.0.1", - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0" + "has": "^1.0.1", + "postcss": "^5.0.10", + "postcss-value-parser": "^3.1.1" } }, "postcss-merge-longhand": { @@ -4697,7 +4716,7 @@ "integrity": "sha1-I9kM0Sewp3mUkVMyc5A0oaTz1lg=", "dev": true, "requires": { - "postcss": "5.2.17" + "postcss": "^5.0.4" } }, "postcss-merge-rules": { @@ -4706,11 +4725,11 @@ "integrity": "sha1-0d9d+qexrMO+VT8OnhDofGG19yE=", "dev": true, "requires": { - "browserslist": "1.7.7", - "caniuse-api": "1.6.1", - "postcss": "5.2.17", - "postcss-selector-parser": "2.2.3", - "vendors": "1.0.1" + "browserslist": "^1.5.2", + "caniuse-api": "^1.5.2", + "postcss": "^5.0.4", + "postcss-selector-parser": "^2.2.2", + "vendors": "^1.0.0" } }, "postcss-message-helpers": { @@ -4725,9 +4744,9 @@ "integrity": "sha1-S1jttWZB66fIR0qzUmyv17vey2k=", "dev": true, "requires": { - "object-assign": "4.1.1", - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0" + "object-assign": "^4.0.1", + "postcss": "^5.0.4", + "postcss-value-parser": "^3.0.2" } }, "postcss-minify-gradients": { @@ -4736,8 +4755,8 @@ "integrity": "sha1-Xb2hE3NwP4PPtKPqOIHY11/15uE=", "dev": true, "requires": { - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0" + "postcss": "^5.0.12", + "postcss-value-parser": "^3.3.0" } }, "postcss-minify-params": { @@ -4746,10 +4765,10 @@ "integrity": "sha1-rSzgcTc7lDs9kwo/pZo1jCjW8fM=", "dev": true, "requires": { - "alphanum-sort": "1.0.2", - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0", - "uniqs": "2.0.0" + "alphanum-sort": "^1.0.1", + "postcss": "^5.0.2", + "postcss-value-parser": "^3.0.2", + "uniqs": "^2.0.0" } }, "postcss-minify-selectors": { @@ -4758,10 +4777,10 @@ "integrity": "sha1-ssapjAByz5G5MtGkllCBFDEXNb8=", "dev": true, "requires": { - "alphanum-sort": "1.0.2", - "has": "1.0.1", - "postcss": "5.2.17", - "postcss-selector-parser": "2.2.3" + "alphanum-sort": "^1.0.2", + "has": "^1.0.1", + "postcss": "^5.0.14", + "postcss-selector-parser": "^2.0.0" } }, "postcss-modules-extract-imports": { @@ -4770,7 +4789,7 @@ "integrity": "sha1-j7P++abdBCDT9tQ1PPH/c/Kyo0E=", "dev": true, "requires": { - "postcss": "5.2.17" + "postcss": "^5.0.4" } }, "postcss-modules-local-by-default": { @@ -4779,8 +4798,8 @@ "integrity": "sha1-KaEGc/o30ZJRJlyiujFQ2QQOtM4=", "dev": true, "requires": { - "css-selector-tokenizer": "0.6.0", - "postcss": "5.2.17" + "css-selector-tokenizer": "^0.6.0", + "postcss": "^5.0.4" }, "dependencies": { "css-selector-tokenizer": { @@ -4789,9 +4808,9 @@ "integrity": "sha1-ZEX1gseTDSQdzFAHpD1vy48HMVI=", "dev": true, "requires": { - "cssesc": "0.1.0", - "fastparse": "1.1.1", - "regexpu-core": "1.0.0" + "cssesc": "^0.1.0", + "fastparse": "^1.1.1", + "regexpu-core": "^1.0.0" } }, "regexpu-core": { @@ -4800,9 +4819,9 @@ "integrity": "sha1-hqdj9Y7k18L2sQLkdkBQ3n7ZDGs=", "dev": true, "requires": { - "regenerate": "1.3.2", - "regjsgen": "0.2.0", - "regjsparser": "0.1.5" + "regenerate": "^1.2.1", + "regjsgen": "^0.2.0", + "regjsparser": "^0.1.4" } } } @@ -4813,8 +4832,8 @@ "integrity": "sha1-/5dzleXgYgLXNiKQuIsejNBJ3ik=", "dev": true, "requires": { - "css-selector-tokenizer": "0.6.0", - "postcss": "5.2.17" + "css-selector-tokenizer": "^0.6.0", + "postcss": "^5.0.4" }, "dependencies": { "css-selector-tokenizer": { @@ -4823,9 +4842,9 @@ "integrity": "sha1-ZEX1gseTDSQdzFAHpD1vy48HMVI=", "dev": true, "requires": { - "cssesc": "0.1.0", - "fastparse": "1.1.1", - "regexpu-core": "1.0.0" + "cssesc": "^0.1.0", + "fastparse": "^1.1.1", + "regexpu-core": "^1.0.0" } }, "regexpu-core": { @@ -4834,9 +4853,9 @@ "integrity": "sha1-hqdj9Y7k18L2sQLkdkBQ3n7ZDGs=", "dev": true, "requires": { - "regenerate": "1.3.2", - "regjsgen": "0.2.0", - "regjsparser": "0.1.5" + "regenerate": "^1.2.1", + "regjsgen": "^0.2.0", + "regjsparser": "^0.1.4" } } } @@ -4847,8 +4866,8 @@ "integrity": "sha1-8OfUdv4e2IxeTH+XUzo+dyrZTKE=", "dev": true, "requires": { - "icss-replace-symbols": "1.0.2", - "postcss": "5.2.17" + "icss-replace-symbols": "^1.0.2", + "postcss": "^5.0.14" } }, "postcss-normalize-charset": { @@ -4857,7 +4876,7 @@ "integrity": "sha1-757nEhLX/nWceO0WL2HtYrXLk/E=", "dev": true, "requires": { - "postcss": "5.2.17" + "postcss": "^5.0.5" } }, "postcss-normalize-url": { @@ -4866,10 +4885,10 @@ "integrity": "sha1-EI90s/L82viRov+j6kWSJ5/HgiI=", "dev": true, "requires": { - "is-absolute-url": "2.1.0", - "normalize-url": "1.9.1", - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0" + "is-absolute-url": "^2.0.0", + "normalize-url": "^1.4.0", + "postcss": "^5.0.14", + "postcss-value-parser": "^3.2.3" } }, "postcss-ordered-values": { @@ -4878,8 +4897,8 @@ "integrity": "sha1-7sbCpntsQSqNsgQud/6NpD+VwR0=", "dev": true, "requires": { - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0" + "postcss": "^5.0.4", + "postcss-value-parser": "^3.0.1" } }, "postcss-reduce-idents": { @@ -4888,8 +4907,8 @@ "integrity": "sha1-wsbSDMlYKE9qv75j92Cb9AkFmtM=", "dev": true, "requires": { - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0" + "postcss": "^5.0.4", + "postcss-value-parser": "^3.0.2" } }, "postcss-reduce-initial": { @@ -4898,7 +4917,7 @@ "integrity": "sha1-aPgGlfBF0IJjqHmtJA343WT2ROo=", "dev": true, "requires": { - "postcss": "5.2.17" + "postcss": "^5.0.4" } }, "postcss-reduce-transforms": { @@ -4907,9 +4926,9 @@ "integrity": "sha1-/3b02CEkN7McKYpC0uFEQCV3GuE=", "dev": true, "requires": { - "has": "1.0.1", - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0" + "has": "^1.0.1", + "postcss": "^5.0.8", + "postcss-value-parser": "^3.0.1" } }, "postcss-selector-parser": { @@ -4918,9 +4937,9 @@ "integrity": "sha1-+UN3iGBsPJrO4W/+jYsWKX8nu5A=", "dev": true, "requires": { - "flatten": "1.0.2", - "indexes-of": "1.0.1", - "uniq": "1.0.1" + "flatten": "^1.0.2", + "indexes-of": "^1.0.1", + "uniq": "^1.0.1" } }, "postcss-svgo": { @@ -4929,10 +4948,10 @@ "integrity": "sha1-tt8YqmE7Zm4TPwittSGcJoSsEI0=", "dev": true, "requires": { - "is-svg": "2.1.0", - "postcss": "5.2.17", - "postcss-value-parser": "3.3.0", - "svgo": "0.7.2" + "is-svg": "^2.0.0", + "postcss": "^5.0.14", + "postcss-value-parser": "^3.2.3", + "svgo": "^0.7.0" } }, "postcss-unique-selectors": { @@ -4941,9 +4960,9 @@ "integrity": "sha1-mB1X0p3csz57Hf4f1DuGSfkzyh0=", "dev": true, "requires": { - "alphanum-sort": "1.0.2", - "postcss": "5.2.17", - "uniqs": "2.0.0" + "alphanum-sort": "^1.0.1", + "postcss": "^5.0.4", + "uniqs": "^2.0.0" } }, "postcss-value-parser": { @@ -4958,9 +4977,9 @@ "integrity": "sha1-0hCd3AVbka9n/EyzsCWUZjnSryI=", "dev": true, "requires": { - "has": "1.0.1", - "postcss": "5.2.17", - "uniqs": "2.0.0" + "has": "^1.0.1", + "postcss": "^5.0.4", + "uniqs": "^2.0.0" } }, "prelude-ls": { @@ -5010,7 +5029,7 @@ "resolved": "http://registry.npmjs.org/promise/-/promise-8.0.1.tgz", "integrity": "sha1-5F1osAoXZHttpxG/he1u1HII9FA=", "requires": { - "asap": "2.0.6" + "asap": "~2.0.3" } }, "prop-types": { @@ -5018,8 +5037,8 @@ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.6.2.tgz", "integrity": "sha512-3pboPvLiWD7dkI3qf3KbUe6hKFKa52w+AE0VCqECtf+QHAKgOL37tTaNCnuX1nAAQ4ZhyP+kYVKf8rLmJ/feDQ==", "requires": { - "loose-envify": "1.3.1", - "object-assign": "4.1.1" + "loose-envify": "^1.3.1", + "object-assign": "^4.1.1" } }, "prr": { @@ -5034,11 +5053,11 @@ "integrity": "sha1-OfaZ86RlYN1eusvKaTyvfGXBjMY=", "dev": true, "requires": { - "bn.js": "4.11.6", - "browserify-rsa": "4.0.1", - "create-hash": "1.1.2", - "parse-asn1": "5.1.0", - "randombytes": "2.0.3" + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1" } }, "punycode": { @@ -5059,8 +5078,8 @@ "integrity": "sha1-u7aTucqRXCMlFbIosaArYJBD2+s=", "dev": true, "requires": { - "object-assign": "4.1.1", - "strict-uri-encode": "1.1.0" + "object-assign": "^4.1.0", + "strict-uri-encode": "^1.0.0" } }, "querystring": { @@ -5081,8 +5100,8 @@ "integrity": "sha1-EQ3Kv/OX6dz/fAeJzMCkmt8exbs=", "dev": true, "requires": { - "is-number": "2.1.0", - "kind-of": "3.2.0" + "is-number": "^2.0.2", + "kind-of": "^3.0.2" } }, "randombytes": { @@ -5096,10 +5115,10 @@ "resolved": "https://registry.npmjs.org/react/-/react-16.4.1.tgz", "integrity": "sha512-3GEs0giKp6E0Oh/Y9ZC60CmYgUPnp7voH9fbjWsvXtYFb4EWtgQub0ADSq0sJR0BbHc4FThLLtzlcFaFXIorwg==", "requires": { - "fbjs": "0.8.17", - "loose-envify": "1.3.1", - "object-assign": "4.1.1", - "prop-types": "15.6.2" + "fbjs": "^0.8.16", + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1", + "prop-types": "^15.6.0" }, "dependencies": { "fbjs": { @@ -5107,13 +5126,13 @@ "resolved": "https://registry.npmjs.org/fbjs/-/fbjs-0.8.17.tgz", "integrity": "sha1-xNWY6taUkRJlPWWIsBpc3Nn5D90=", "requires": { - "core-js": "1.2.7", - "isomorphic-fetch": "2.2.1", - "loose-envify": "1.3.1", - "object-assign": "4.1.1", - "promise": "7.3.1", - "setimmediate": "1.0.5", - "ua-parser-js": "0.7.18" + "core-js": "^1.0.0", + "isomorphic-fetch": "^2.1.1", + "loose-envify": "^1.0.0", + "object-assign": "^4.1.0", + "promise": "^7.1.1", + "setimmediate": "^1.0.5", + "ua-parser-js": "^0.7.18" } }, "promise": { @@ -5121,7 +5140,7 @@ "resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz", "integrity": "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg==", "requires": { - "asap": "2.0.6" + "asap": "~2.0.3" } }, "ua-parser-js": { @@ -5136,9 +5155,9 @@ "resolved": "https://registry.npmjs.org/react-autosuggest/-/react-autosuggest-9.3.4.tgz", "integrity": "sha512-vcAsZw+6zkjimni4aun1tvuzVCGilmFihAgF8yCeVm/p82ssGgtQb0pnNCcEBcPzPTLJjQc2O8dLJidoOyjlcA==", "requires": { - "prop-types": "15.6.2", - "react-autowhatever": "10.1.2", - "shallow-equal": "1.0.0" + "prop-types": "^15.5.10", + "react-autowhatever": "^10.1.0", + "shallow-equal": "^1.0.0" } }, "react-autowhatever": { @@ -5146,9 +5165,9 @@ "resolved": "https://registry.npmjs.org/react-autowhatever/-/react-autowhatever-10.1.2.tgz", "integrity": "sha512-+0XgELT1LF7hHEJv5H5Zwkfb4Q1rqmMZZ5U/XJ2J+UcSPRKnG6CqEjXUJ+hYLXDHgvDqwEN5PBdxczD5rHvOuA==", "requires": { - "prop-types": "15.6.2", - "react-themeable": "1.1.0", - "section-iterator": "2.0.0" + "prop-types": "^15.5.8", + "react-themeable": "^1.1.0", + "section-iterator": "^2.0.0" } }, "react-dom": { @@ -5156,10 +5175,10 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.4.1.tgz", "integrity": "sha512-1Gin+wghF/7gl4Cqcvr1DxFX2Osz7ugxSwl6gBqCMpdrxHjIFUS7GYxrFftZ9Ln44FHw0JxCFD9YtZsrbR5/4A==", "requires": { - "fbjs": "0.8.17", - "loose-envify": "1.3.1", - "object-assign": "4.1.1", - "prop-types": "15.6.2" + "fbjs": "^0.8.16", + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1", + "prop-types": "^15.6.0" }, "dependencies": { "fbjs": { @@ -5167,13 +5186,13 @@ "resolved": "https://registry.npmjs.org/fbjs/-/fbjs-0.8.17.tgz", "integrity": "sha1-xNWY6taUkRJlPWWIsBpc3Nn5D90=", "requires": { - "core-js": "1.2.7", - "isomorphic-fetch": "2.2.1", - "loose-envify": "1.3.1", - "object-assign": "4.1.1", - "promise": "7.3.1", - "setimmediate": "1.0.5", - "ua-parser-js": "0.7.18" + "core-js": "^1.0.0", + "isomorphic-fetch": "^2.1.1", + "loose-envify": "^1.0.0", + "object-assign": "^4.1.0", + "promise": "^7.1.1", + "setimmediate": "^1.0.5", + "ua-parser-js": "^0.7.18" } }, "promise": { @@ -5181,7 +5200,7 @@ "resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz", "integrity": "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg==", "requires": { - "asap": "2.0.6" + "asap": "~2.0.3" } }, "ua-parser-js": { @@ -5196,7 +5215,7 @@ "resolved": "https://registry.npmjs.org/react-themeable/-/react-themeable-1.1.0.tgz", "integrity": "sha1-fURm3ZsrX6dQWHJ4JenxUro3mg4=", "requires": { - "object-assign": "3.0.0" + "object-assign": "^3.0.0" }, "dependencies": { "object-assign": { @@ -5212,9 +5231,9 @@ "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", "dev": true, "requires": { - "load-json-file": "1.1.0", - "normalize-package-data": "2.3.8", - "path-type": "1.1.0" + "load-json-file": "^1.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^1.0.0" } }, "read-pkg-up": { @@ -5223,8 +5242,8 @@ "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", "dev": true, "requires": { - "find-up": "1.1.2", - "read-pkg": "1.1.0" + "find-up": "^1.0.0", + "read-pkg": "^1.0.0" }, "dependencies": { "find-up": { @@ -5233,8 +5252,8 @@ "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", "dev": true, "requires": { - "path-exists": "2.1.0", - "pinkie-promise": "2.0.1" + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" } }, "path-exists": { @@ -5243,7 +5262,7 @@ "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", "dev": true, "requires": { - "pinkie-promise": "2.0.1" + "pinkie-promise": "^2.0.0" } } } @@ -5254,13 +5273,13 @@ "integrity": "sha1-z3jsb0ptHrQ9JkiMrJfwQudLf8g=", "dev": true, "requires": { - "buffer-shims": "1.0.0", - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "string_decoder": "1.0.0", - "util-deprecate": "1.0.2" + "buffer-shims": "~1.0.0", + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "~1.0.0", + "process-nextick-args": "~1.0.6", + "string_decoder": "~1.0.0", + "util-deprecate": "~1.0.1" } }, "readdirp": { @@ -5269,10 +5288,10 @@ "integrity": "sha1-TtCtBg3zBzMAxIRANz9y0cxkLXg=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "minimatch": "3.0.3", - "readable-stream": "2.2.9", - "set-immediate-shim": "1.0.1" + "graceful-fs": "^4.1.2", + "minimatch": "^3.0.2", + "readable-stream": "^2.0.2", + "set-immediate-shim": "^1.0.1" } }, "readline2": { @@ -5281,8 +5300,8 @@ "integrity": "sha1-QQWWCP/BVHV7cV2ZidGZ/783LjU=", "dev": true, "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", "mute-stream": "0.0.5" } }, @@ -5292,7 +5311,7 @@ "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", "dev": true, "requires": { - "resolve": "1.3.3" + "resolve": "^1.1.6" } }, "reduce-css-calc": { @@ -5301,9 +5320,9 @@ "integrity": "sha1-dHyRTgSWFKTJz7umKYca0dKSdxY=", "dev": true, "requires": { - "balanced-match": "0.4.2", - "math-expression-evaluator": "1.2.16", - "reduce-function-call": "1.0.2" + "balanced-match": "^0.4.2", + "math-expression-evaluator": "^1.2.14", + "reduce-function-call": "^1.0.1" } }, "reduce-function-call": { @@ -5312,7 +5331,7 @@ "integrity": "sha1-WiAL+S4ON3UXUv5FsKszD9S2vpk=", "dev": true, "requires": { - "balanced-match": "0.4.2" + "balanced-match": "^0.4.2" } }, "regenerate": { @@ -5333,9 +5352,9 @@ "integrity": "sha1-On0GdSDLe3F2dp61/4aGkb7+EoM=", "dev": true, "requires": { - "babel-runtime": "6.23.0", - "babel-types": "6.24.1", - "private": "0.1.7" + "babel-runtime": "^6.18.0", + "babel-types": "^6.19.0", + "private": "^0.1.6" } }, "regex-cache": { @@ -5344,8 +5363,8 @@ "integrity": "sha1-mxpsNdTQ3871cRrmUejp09cRQUU=", "dev": true, "requires": { - "is-equal-shallow": "0.1.3", - "is-primitive": "2.0.0" + "is-equal-shallow": "^0.1.3", + "is-primitive": "^2.0.0" } }, "regexpu-core": { @@ -5354,9 +5373,9 @@ "integrity": "sha1-SdA4g3uNz4v6W5pCE5k45uoq4kA=", "dev": true, "requires": { - "regenerate": "1.3.2", - "regjsgen": "0.2.0", - "regjsparser": "0.1.5" + "regenerate": "^1.2.1", + "regjsgen": "^0.2.0", + "regjsparser": "^0.1.4" } }, "regjsgen": { @@ -5371,7 +5390,7 @@ "integrity": "sha1-fuj4Tcb6eS0/0K4ijSS9lJ6tIFw=", "dev": true, "requires": { - "jsesc": "0.5.0" + "jsesc": "~0.5.0" }, "dependencies": { "jsesc": { @@ -5406,7 +5425,7 @@ "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", "dev": true, "requires": { - "is-finite": "1.0.2" + "is-finite": "^1.0.0" } }, "require-directory": { @@ -5427,8 +5446,8 @@ "integrity": "sha1-Tg1W1slmL9MeQwEcS5WqSZVUIdM=", "dev": true, "requires": { - "caller-path": "0.1.0", - "resolve-from": "1.0.1" + "caller-path": "^0.1.0", + "resolve-from": "^1.0.0" } }, "resolve": { @@ -5437,7 +5456,7 @@ "integrity": "sha1-ZVkHw0aahoDcLeOidaj91paR8OU=", "dev": true, "requires": { - "path-parse": "1.0.5" + "path-parse": "^1.0.5" } }, "resolve-from": { @@ -5452,8 +5471,8 @@ "integrity": "sha1-NGYfRohjJ/7SmRR5FSJS35LapUE=", "dev": true, "requires": { - "exit-hook": "1.1.1", - "onetime": "1.1.0" + "exit-hook": "^1.0.0", + "onetime": "^1.0.0" } }, "right-align": { @@ -5462,7 +5481,7 @@ "integrity": "sha1-YTObci/mo1FWiSENJOFMlhSGE+8=", "dev": true, "requires": { - "align-text": "0.1.4" + "align-text": "^0.1.1" } }, "rimraf": { @@ -5471,7 +5490,7 @@ "integrity": "sha1-wjOOxkPfeht/5cVPqG9XQopV8z0=", "dev": true, "requires": { - "glob": "7.1.1" + "glob": "^7.0.5" } }, "ripemd160": { @@ -5486,7 +5505,7 @@ "integrity": "sha1-yK1KXhEGYeQCp9IbUw4AnyX444k=", "dev": true, "requires": { - "once": "1.4.0" + "once": "^1.3.0" } }, "rx-lite": { @@ -5535,7 +5554,7 @@ "integrity": "sha1-NwaMLEdra69ALRSknGf1l5IfY08=", "dev": true, "requires": { - "inherits": "2.0.3" + "inherits": "^2.0.1" } }, "shallow-equal": { @@ -5549,9 +5568,9 @@ "integrity": "sha1-svXHfvlxSPS09uImguELuoZnz/E=", "dev": true, "requires": { - "glob": "7.1.1", - "interpret": "1.0.3", - "rechoir": "0.6.2" + "glob": "^7.0.0", + "interpret": "^1.0.0", + "rechoir": "^0.6.2" } }, "slash": { @@ -5572,7 +5591,7 @@ "integrity": "sha1-RBttTTRnmPG05J6JIK37oOVD+a0=", "dev": true, "requires": { - "is-plain-obj": "1.1.0" + "is-plain-obj": "^1.0.0" } }, "source-list-map": { @@ -5593,7 +5612,7 @@ "integrity": "sha1-nURjdyWYuGJxtPUj9sH04Cp9au8=", "dev": true, "requires": { - "source-map": "0.5.6" + "source-map": "^0.5.6" } }, "spdx-correct": { @@ -5602,7 +5621,7 @@ "integrity": "sha1-SzBz2TP/UfORLwOsVRlJikFQ20A=", "dev": true, "requires": { - "spdx-license-ids": "1.2.2" + "spdx-license-ids": "^1.0.2" } }, "spdx-expression-parse": { @@ -5629,8 +5648,8 @@ "integrity": "sha1-ZiZu5fm9uZQKTkUUyvtDu3Hlyds=", "dev": true, "requires": { - "inherits": "2.0.3", - "readable-stream": "2.2.9" + "inherits": "~2.0.1", + "readable-stream": "^2.0.2" } }, "stream-http": { @@ -5639,11 +5658,11 @@ "integrity": "sha1-zsH047SUvEqBtFGAiXD4sgtO1fY=", "dev": true, "requires": { - "builtin-status-codes": "3.0.0", - "inherits": "2.0.3", - "readable-stream": "2.2.9", - "to-arraybuffer": "1.0.1", - "xtend": "4.0.1" + "builtin-status-codes": "^3.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.2.6", + "to-arraybuffer": "^1.0.0", + "xtend": "^4.0.0" } }, "strict-uri-encode": { @@ -5658,9 +5677,9 @@ "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", "dev": true, "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" } }, "string_decoder": { @@ -5669,7 +5688,7 @@ "integrity": "sha1-8G9BFXtmTYYGn4S9vcmw2KsoFmc=", "dev": true, "requires": { - "buffer-shims": "1.0.0" + "buffer-shims": "~1.0.0" } }, "strip-ansi": { @@ -5678,7 +5697,7 @@ "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "dev": true, "requires": { - "ansi-regex": "2.1.1" + "ansi-regex": "^2.0.0" } }, "strip-bom": { @@ -5687,7 +5706,7 @@ "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", "dev": true, "requires": { - "is-utf8": "0.2.1" + "is-utf8": "^0.2.0" } }, "strip-json-comments": { @@ -5708,13 +5727,13 @@ "integrity": "sha1-n1dyQTlSE1xv779Ar+ak+qiLS7U=", "dev": true, "requires": { - "coa": "1.0.1", - "colors": "1.1.2", - "csso": "2.3.2", - "js-yaml": "3.7.0", - "mkdirp": "0.5.1", - "sax": "1.2.2", - "whet.extend": "0.9.9" + "coa": "~1.0.1", + "colors": "~1.1.2", + "csso": "~2.3.1", + "js-yaml": "~3.7.0", + "mkdirp": "~0.5.1", + "sax": "~1.2.1", + "whet.extend": "~0.9.9" } }, "table": { @@ -5723,12 +5742,12 @@ "integrity": "sha1-K7xULw/amGGnVdOUf+/Ys/UThV8=", "dev": true, "requires": { - "ajv": "4.11.7", - "ajv-keywords": "1.5.1", - "chalk": "1.1.3", - "lodash": "4.17.4", + "ajv": "^4.7.0", + "ajv-keywords": "^1.0.0", + "chalk": "^1.1.1", + "lodash": "^4.0.0", "slice-ansi": "0.0.4", - "string-width": "2.0.0" + "string-width": "^2.0.0" }, "dependencies": { "is-fullwidth-code-point": { @@ -5743,8 +5762,8 @@ "integrity": "sha1-Y1xUNsxypuDDh87KJ41OLuxSaH4=", "dev": true, "requires": { - "is-fullwidth-code-point": "2.0.0", - "strip-ansi": "3.0.1" + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^3.0.0" } } } @@ -5773,7 +5792,7 @@ "integrity": "sha1-q0iDz1l9zVCvIRNJoA+8pWrIa4Y=", "dev": true, "requires": { - "setimmediate": "1.0.5" + "setimmediate": "^1.0.4" } }, "to-arraybuffer": { @@ -5812,7 +5831,7 @@ "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", "dev": true, "requires": { - "prelude-ls": "1.1.2" + "prelude-ls": "~1.1.2" } }, "typedarray": { @@ -5832,9 +5851,9 @@ "integrity": "sha1-1Uk0d4qNoUkD+imjJvskwKtRoaA=", "dev": true, "requires": { - "source-map": "0.5.6", - "uglify-to-browserify": "1.0.2", - "yargs": "3.10.0" + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" }, "dependencies": { "yargs": { @@ -5843,9 +5862,9 @@ "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=", "dev": true, "requires": { - "camelcase": "1.2.1", - "cliui": "2.1.0", - "decamelize": "1.2.0", + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", "window-size": "0.1.0" } } @@ -5870,7 +5889,7 @@ "integrity": "sha1-iSIN32t1GuUrX3JISGNShZa7hME=", "dev": true, "requires": { - "macaddress": "0.2.8" + "macaddress": "^0.2.8" } }, "uniqs": { @@ -5903,7 +5922,7 @@ "integrity": "sha1-nHC/2Babwdy/SGBODwS4tJzenp8=", "dev": true, "requires": { - "os-homedir": "1.0.2" + "os-homedir": "^1.0.0" } }, "util": { @@ -5935,8 +5954,8 @@ "integrity": "sha1-KAS6vnEq0zeUWaz74kdGqywwP7w=", "dev": true, "requires": { - "spdx-correct": "1.0.2", - "spdx-expression-parse": "1.0.4" + "spdx-correct": "~1.0.0", + "spdx-expression-parse": "~1.0.0" } }, "vendors": { @@ -5960,9 +5979,9 @@ "integrity": "sha1-fYaTkHsozmAT5/NhCqKhrPB9rYc=", "dev": true, "requires": { - "async": "2.3.0", - "chokidar": "1.6.1", - "graceful-fs": "4.1.11" + "async": "^2.1.2", + "chokidar": "^1.4.3", + "graceful-fs": "^4.1.2" } }, "webpack": { @@ -5971,27 +5990,27 @@ "integrity": "sha1-FakdvjSWbYpLmcfWVu/ZKi5ab2o=", "dev": true, "requires": { - "acorn": "5.0.3", - "acorn-dynamic-import": "2.0.2", - "ajv": "4.11.7", - "ajv-keywords": "1.5.1", - "async": "2.3.0", - "enhanced-resolve": "3.1.0", - "interpret": "1.0.3", - "json-loader": "0.5.4", - "json5": "0.5.1", - "loader-runner": "2.3.0", - "loader-utils": "0.2.17", - "memory-fs": "0.4.1", - "mkdirp": "0.5.1", - "node-libs-browser": "2.0.0", - "source-map": "0.5.6", - "supports-color": "3.2.3", - "tapable": "0.2.6", - "uglify-js": "2.8.22", - "watchpack": "1.3.1", - "webpack-sources": "0.2.3", - "yargs": "6.6.0" + "acorn": "^5.0.0", + "acorn-dynamic-import": "^2.0.0", + "ajv": "^4.7.0", + "ajv-keywords": "^1.1.1", + "async": "^2.1.2", + "enhanced-resolve": "^3.0.0", + "interpret": "^1.0.0", + "json-loader": "^0.5.4", + "json5": "^0.5.1", + "loader-runner": "^2.3.0", + "loader-utils": "^0.2.16", + "memory-fs": "~0.4.1", + "mkdirp": "~0.5.0", + "node-libs-browser": "^2.0.0", + "source-map": "^0.5.3", + "supports-color": "^3.1.0", + "tapable": "~0.2.5", + "uglify-js": "^2.8.5", + "watchpack": "^1.3.1", + "webpack-sources": "^0.2.3", + "yargs": "^6.0.0" }, "dependencies": { "source-list-map": { @@ -6006,7 +6025,7 @@ "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", "dev": true, "requires": { - "has-flag": "1.0.0" + "has-flag": "^1.0.0" } }, "webpack-sources": { @@ -6015,8 +6034,8 @@ "integrity": "sha1-F8Yr+vE8cH+dAsR54Nzd6DgGl/s=", "dev": true, "requires": { - "source-list-map": "1.1.1", - "source-map": "0.5.6" + "source-list-map": "^1.1.1", + "source-map": "~0.5.3" } } } @@ -6027,8 +6046,8 @@ "integrity": "sha1-qh86vw8NdNtxEcQOUAuE+WZkB1A=", "dev": true, "requires": { - "source-list-map": "0.1.8", - "source-map": "0.5.6" + "source-list-map": "~0.1.7", + "source-map": "~0.5.3" } }, "whatwg-fetch": { @@ -6066,8 +6085,8 @@ "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", "dev": true, "requires": { - "string-width": "1.0.2", - "strip-ansi": "3.0.1" + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1" } }, "wrappy": { @@ -6082,7 +6101,7 @@ "integrity": "sha1-X8A4KOJkzqP+kUVUdvejxWbLB1c=", "dev": true, "requires": { - "mkdirp": "0.5.1" + "mkdirp": "^0.5.1" } }, "xtend": { @@ -6103,19 +6122,19 @@ "integrity": "sha1-eC7CHvQDNF+DCoCMo9UTr1YGUgg=", "dev": true, "requires": { - "camelcase": "3.0.0", - "cliui": "3.2.0", - "decamelize": "1.2.0", - "get-caller-file": "1.0.2", - "os-locale": "1.4.0", - "read-pkg-up": "1.0.1", - "require-directory": "2.1.1", - "require-main-filename": "1.0.1", - "set-blocking": "2.0.0", - "string-width": "1.0.2", - "which-module": "1.0.0", - "y18n": "3.2.1", - "yargs-parser": "4.2.1" + "camelcase": "^3.0.0", + "cliui": "^3.2.0", + "decamelize": "^1.1.1", + "get-caller-file": "^1.0.1", + "os-locale": "^1.4.0", + "read-pkg-up": "^1.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^1.0.2", + "which-module": "^1.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^4.2.0" }, "dependencies": { "camelcase": { @@ -6130,9 +6149,9 @@ "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=", "dev": true, "requires": { - "string-width": "1.0.2", - "strip-ansi": "3.0.1", - "wrap-ansi": "2.1.0" + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wrap-ansi": "^2.0.0" } } } @@ -6143,7 +6162,7 @@ "integrity": "sha1-KczqwNxPA8bIe0qfIX3RjJ90hxw=", "dev": true, "requires": { - "camelcase": "3.0.0" + "camelcase": "^3.0.0" }, "dependencies": { "camelcase": { diff --git a/package.json b/package.json index 2210848..dca81e3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "wagtailmodelchoosers", - "version": "2.0b1", + "version": "2.0.0b1", "description": "Allows you to pick generic models (rather than snippets or pages)", "main": "setup.py", "keywords": [], diff --git a/setup.py b/setup.py index c8cbc51..d4b057b 100644 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ install_requires = [ 'wagtail>=2', # Depends on Wagtail's Django and Django RestFramework depencencies - 'django-filter>=1.1.0,<2', + 'django-filter>=2', ] # Testing dependencies diff --git a/wagtailmodelchoosers/client/components/AutoComplete.js b/wagtailmodelchoosers/client/components/AutoComplete.js index afe3d11..4ad233b 100644 --- a/wagtailmodelchoosers/client/components/AutoComplete.js +++ b/wagtailmodelchoosers/client/components/AutoComplete.js @@ -40,13 +40,11 @@ class AutoComplete extends Component { onSuggestionsClearRequested() { const { onLoadSuggestions } = this.props; - this.setState( { - suggestions: [], loading: false, }, - () => onLoadSuggestions([]), + () => onLoadSuggestions(this.state.suggestions), ); } @@ -58,6 +56,7 @@ class AutoComplete extends Component { }, () => { onChange(newValue); }); + } loadSuggestions(suggestionValue) { diff --git a/wagtailmodelchoosers/static/wagtailmodelchoosers/polyfills.js b/wagtailmodelchoosers/static/wagtailmodelchoosers/polyfills.js new file mode 100644 index 0000000..ec72997 --- /dev/null +++ b/wagtailmodelchoosers/static/wagtailmodelchoosers/polyfills.js @@ -0,0 +1,1330 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 96); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ 11: +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), + +/***/ 76: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var asap = __webpack_require__(94); + +function noop() {} + +// States: +// +// 0 - pending +// 1 - fulfilled with _value +// 2 - rejected with _value +// 3 - adopted the state of another promise, _value +// +// once the state is no longer pending (0) it is immutable + +// All `_` prefixed properties will be reduced to `_{random number}` +// at build time to obfuscate them and discourage their use. +// We don't use symbols or Object.defineProperty to fully hide them +// because the performance isn't good enough. + + +// to avoid using try/catch inside critical functions, we +// extract them to here. +var LAST_ERROR = null; +var IS_ERROR = {}; +function getThen(obj) { + try { + return obj.then; + } catch (ex) { + LAST_ERROR = ex; + return IS_ERROR; + } +} + +function tryCallOne(fn, a) { + try { + return fn(a); + } catch (ex) { + LAST_ERROR = ex; + return IS_ERROR; + } +} +function tryCallTwo(fn, a, b) { + try { + fn(a, b); + } catch (ex) { + LAST_ERROR = ex; + return IS_ERROR; + } +} + +module.exports = Promise; + +function Promise(fn) { + if (typeof this !== 'object') { + throw new TypeError('Promises must be constructed via new'); + } + if (typeof fn !== 'function') { + throw new TypeError('Promise constructor\'s argument is not a function'); + } + this._75 = 0; + this._83 = 0; + this._18 = null; + this._38 = null; + if (fn === noop) return; + doResolve(fn, this); +} +Promise._47 = null; +Promise._71 = null; +Promise._44 = noop; + +Promise.prototype.then = function(onFulfilled, onRejected) { + if (this.constructor !== Promise) { + return safeThen(this, onFulfilled, onRejected); + } + var res = new Promise(noop); + handle(this, new Handler(onFulfilled, onRejected, res)); + return res; +}; + +function safeThen(self, onFulfilled, onRejected) { + return new self.constructor(function (resolve, reject) { + var res = new Promise(noop); + res.then(resolve, reject); + handle(self, new Handler(onFulfilled, onRejected, res)); + }); +} +function handle(self, deferred) { + while (self._83 === 3) { + self = self._18; + } + if (Promise._47) { + Promise._47(self); + } + if (self._83 === 0) { + if (self._75 === 0) { + self._75 = 1; + self._38 = deferred; + return; + } + if (self._75 === 1) { + self._75 = 2; + self._38 = [self._38, deferred]; + return; + } + self._38.push(deferred); + return; + } + handleResolved(self, deferred); +} + +function handleResolved(self, deferred) { + asap(function() { + var cb = self._83 === 1 ? deferred.onFulfilled : deferred.onRejected; + if (cb === null) { + if (self._83 === 1) { + resolve(deferred.promise, self._18); + } else { + reject(deferred.promise, self._18); + } + return; + } + var ret = tryCallOne(cb, self._18); + if (ret === IS_ERROR) { + reject(deferred.promise, LAST_ERROR); + } else { + resolve(deferred.promise, ret); + } + }); +} +function resolve(self, newValue) { + // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure + if (newValue === self) { + return reject( + self, + new TypeError('A promise cannot be resolved with itself.') + ); + } + if ( + newValue && + (typeof newValue === 'object' || typeof newValue === 'function') + ) { + var then = getThen(newValue); + if (then === IS_ERROR) { + return reject(self, LAST_ERROR); + } + if ( + then === self.then && + newValue instanceof Promise + ) { + self._83 = 3; + self._18 = newValue; + finale(self); + return; + } else if (typeof then === 'function') { + doResolve(then.bind(newValue), self); + return; + } + } + self._83 = 1; + self._18 = newValue; + finale(self); +} + +function reject(self, newValue) { + self._83 = 2; + self._18 = newValue; + if (Promise._71) { + Promise._71(self, newValue); + } + finale(self); +} +function finale(self) { + if (self._75 === 1) { + handle(self, self._38); + self._38 = null; + } + if (self._75 === 2) { + for (var i = 0; i < self._38.length; i++) { + handle(self, self._38[i]); + } + self._38 = null; + } +} + +function Handler(onFulfilled, onRejected, promise){ + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.promise = promise; +} + +/** + * Take a potentially misbehaving resolver function and make sure + * onFulfilled and onRejected are only called once. + * + * Makes no guarantees about asynchrony. + */ +function doResolve(fn, promise) { + var done = false; + var res = tryCallTwo(fn, function (value) { + if (done) return; + done = true; + resolve(promise, value); + }, function (reason) { + if (done) return; + done = true; + reject(promise, reason); + }); + if (!done && res === IS_ERROR) { + done = true; + reject(promise, LAST_ERROR); + } +} + + +/***/ }), + +/***/ 91: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +//This file contains the ES6 extensions to the core Promises/A+ API + +var Promise = __webpack_require__(76); + +module.exports = Promise; + +/* Static Functions */ + +var TRUE = valuePromise(true); +var FALSE = valuePromise(false); +var NULL = valuePromise(null); +var UNDEFINED = valuePromise(undefined); +var ZERO = valuePromise(0); +var EMPTYSTRING = valuePromise(''); + +function valuePromise(value) { + var p = new Promise(Promise._44); + p._83 = 1; + p._18 = value; + return p; +} +Promise.resolve = function (value) { + if (value instanceof Promise) return value; + + if (value === null) return NULL; + if (value === undefined) return UNDEFINED; + if (value === true) return TRUE; + if (value === false) return FALSE; + if (value === 0) return ZERO; + if (value === '') return EMPTYSTRING; + + if (typeof value === 'object' || typeof value === 'function') { + try { + var then = value.then; + if (typeof then === 'function') { + return new Promise(then.bind(value)); + } + } catch (ex) { + return new Promise(function (resolve, reject) { + reject(ex); + }); + } + } + return valuePromise(value); +}; + +Promise.all = function (arr) { + var args = Array.prototype.slice.call(arr); + + return new Promise(function (resolve, reject) { + if (args.length === 0) return resolve([]); + var remaining = args.length; + function res(i, val) { + if (val && (typeof val === 'object' || typeof val === 'function')) { + if (val instanceof Promise && val.then === Promise.prototype.then) { + while (val._83 === 3) { + val = val._18; + } + if (val._83 === 1) return res(i, val._18); + if (val._83 === 2) reject(val._18); + val.then(function (val) { + res(i, val); + }, reject); + return; + } else { + var then = val.then; + if (typeof then === 'function') { + var p = new Promise(then.bind(val)); + p.then(function (val) { + res(i, val); + }, reject); + return; + } + } + } + args[i] = val; + if (--remaining === 0) { + resolve(args); + } + } + for (var i = 0; i < args.length; i++) { + res(i, args[i]); + } + }); +}; + +Promise.reject = function (value) { + return new Promise(function (resolve, reject) { + reject(value); + }); +}; + +Promise.race = function (values) { + return new Promise(function (resolve, reject) { + values.forEach(function(value){ + Promise.resolve(value).then(resolve, reject); + }); + }); +}; + +/* Prototype Methods */ + +Promise.prototype['catch'] = function (onRejected) { + return this.then(null, onRejected); +}; + + +/***/ }), + +/***/ 92: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Promise = __webpack_require__(76); + +var DEFAULT_WHITELIST = [ + ReferenceError, + TypeError, + RangeError +]; + +var enabled = false; +exports.disable = disable; +function disable() { + enabled = false; + Promise._47 = null; + Promise._71 = null; +} + +exports.enable = enable; +function enable(options) { + options = options || {}; + if (enabled) disable(); + enabled = true; + var id = 0; + var displayId = 0; + var rejections = {}; + Promise._47 = function (promise) { + if ( + promise._83 === 2 && // IS REJECTED + rejections[promise._56] + ) { + if (rejections[promise._56].logged) { + onHandled(promise._56); + } else { + clearTimeout(rejections[promise._56].timeout); + } + delete rejections[promise._56]; + } + }; + Promise._71 = function (promise, err) { + if (promise._75 === 0) { // not yet handled + promise._56 = id++; + rejections[promise._56] = { + displayId: null, + error: err, + timeout: setTimeout( + onUnhandled.bind(null, promise._56), + // For reference errors and type errors, this almost always + // means the programmer made a mistake, so log them after just + // 100ms + // otherwise, wait 2 seconds to see if they get handled + matchWhitelist(err, DEFAULT_WHITELIST) + ? 100 + : 2000 + ), + logged: false + }; + } + }; + function onUnhandled(id) { + if ( + options.allRejections || + matchWhitelist( + rejections[id].error, + options.whitelist || DEFAULT_WHITELIST + ) + ) { + rejections[id].displayId = displayId++; + if (options.onUnhandled) { + rejections[id].logged = true; + options.onUnhandled( + rejections[id].displayId, + rejections[id].error + ); + } else { + rejections[id].logged = true; + logError( + rejections[id].displayId, + rejections[id].error + ); + } + } + } + function onHandled(id) { + if (rejections[id].logged) { + if (options.onHandled) { + options.onHandled(rejections[id].displayId, rejections[id].error); + } else if (!rejections[id].onUnhandled) { + console.warn( + 'Promise Rejection Handled (id: ' + rejections[id].displayId + '):' + ); + console.warn( + ' This means you can ignore any previous messages of the form "Possible Unhandled Promise Rejection" with id ' + + rejections[id].displayId + '.' + ); + } + } + } +} + +function logError(id, error) { + console.warn('Possible Unhandled Promise Rejection (id: ' + id + '):'); + var errStr = (error && (error.stack || error)) + ''; + errStr.split('\n').forEach(function (line) { + console.warn(' ' + line); + }); +} + +function matchWhitelist(error, list) { + return list.some(function (cls) { + return error instanceof cls; + }); +} + +/***/ }), + +/***/ 93: +/***/ (function(module, exports) { + +(function(self) { + 'use strict'; + + if (self.fetch) { + return + } + + var support = { + searchParams: 'URLSearchParams' in self, + iterable: 'Symbol' in self && 'iterator' in Symbol, + blob: 'FileReader' in self && 'Blob' in self && (function() { + try { + new Blob() + return true + } catch(e) { + return false + } + })(), + formData: 'FormData' in self, + arrayBuffer: 'ArrayBuffer' in self + } + + if (support.arrayBuffer) { + var viewClasses = [ + '[object Int8Array]', + '[object Uint8Array]', + '[object Uint8ClampedArray]', + '[object Int16Array]', + '[object Uint16Array]', + '[object Int32Array]', + '[object Uint32Array]', + '[object Float32Array]', + '[object Float64Array]' + ] + + var isDataView = function(obj) { + return obj && DataView.prototype.isPrototypeOf(obj) + } + + var isArrayBufferView = ArrayBuffer.isView || function(obj) { + return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 + } + } + + function normalizeName(name) { + if (typeof name !== 'string') { + name = String(name) + } + if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { + throw new TypeError('Invalid character in header field name') + } + return name.toLowerCase() + } + + function normalizeValue(value) { + if (typeof value !== 'string') { + value = String(value) + } + return value + } + + // Build a destructive iterator for the value list + function iteratorFor(items) { + var iterator = { + next: function() { + var value = items.shift() + return {done: value === undefined, value: value} + } + } + + if (support.iterable) { + iterator[Symbol.iterator] = function() { + return iterator + } + } + + return iterator + } + + function Headers(headers) { + this.map = {} + + if (headers instanceof Headers) { + headers.forEach(function(value, name) { + this.append(name, value) + }, this) + } else if (Array.isArray(headers)) { + headers.forEach(function(header) { + this.append(header[0], header[1]) + }, this) + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]) + }, this) + } + } + + Headers.prototype.append = function(name, value) { + name = normalizeName(name) + value = normalizeValue(value) + var oldValue = this.map[name] + this.map[name] = oldValue ? oldValue+','+value : value + } + + Headers.prototype['delete'] = function(name) { + delete this.map[normalizeName(name)] + } + + Headers.prototype.get = function(name) { + name = normalizeName(name) + return this.has(name) ? this.map[name] : null + } + + Headers.prototype.has = function(name) { + return this.map.hasOwnProperty(normalizeName(name)) + } + + Headers.prototype.set = function(name, value) { + this.map[normalizeName(name)] = normalizeValue(value) + } + + Headers.prototype.forEach = function(callback, thisArg) { + for (var name in this.map) { + if (this.map.hasOwnProperty(name)) { + callback.call(thisArg, this.map[name], name, this) + } + } + } + + Headers.prototype.keys = function() { + var items = [] + this.forEach(function(value, name) { items.push(name) }) + return iteratorFor(items) + } + + Headers.prototype.values = function() { + var items = [] + this.forEach(function(value) { items.push(value) }) + return iteratorFor(items) + } + + Headers.prototype.entries = function() { + var items = [] + this.forEach(function(value, name) { items.push([name, value]) }) + return iteratorFor(items) + } + + if (support.iterable) { + Headers.prototype[Symbol.iterator] = Headers.prototype.entries + } + + function consumed(body) { + if (body.bodyUsed) { + return Promise.reject(new TypeError('Already read')) + } + body.bodyUsed = true + } + + function fileReaderReady(reader) { + return new Promise(function(resolve, reject) { + reader.onload = function() { + resolve(reader.result) + } + reader.onerror = function() { + reject(reader.error) + } + }) + } + + function readBlobAsArrayBuffer(blob) { + var reader = new FileReader() + var promise = fileReaderReady(reader) + reader.readAsArrayBuffer(blob) + return promise + } + + function readBlobAsText(blob) { + var reader = new FileReader() + var promise = fileReaderReady(reader) + reader.readAsText(blob) + return promise + } + + function readArrayBufferAsText(buf) { + var view = new Uint8Array(buf) + var chars = new Array(view.length) + + for (var i = 0; i < view.length; i++) { + chars[i] = String.fromCharCode(view[i]) + } + return chars.join('') + } + + function bufferClone(buf) { + if (buf.slice) { + return buf.slice(0) + } else { + var view = new Uint8Array(buf.byteLength) + view.set(new Uint8Array(buf)) + return view.buffer + } + } + + function Body() { + this.bodyUsed = false + + this._initBody = function(body) { + this._bodyInit = body + if (!body) { + this._bodyText = '' + } else if (typeof body === 'string') { + this._bodyText = body + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString() + } else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer) + // IE 10-11 can't handle a DataView body. + this._bodyInit = new Blob([this._bodyArrayBuffer]) + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { + this._bodyArrayBuffer = bufferClone(body) + } else { + throw new Error('unsupported BodyInit type') + } + + if (!this.headers.get('content-type')) { + if (typeof body === 'string') { + this.headers.set('content-type', 'text/plain;charset=UTF-8') + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set('content-type', this._bodyBlob.type) + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8') + } + } + } + + if (support.blob) { + this.blob = function() { + var rejected = consumed(this) + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return Promise.resolve(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(new Blob([this._bodyArrayBuffer])) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as blob') + } else { + return Promise.resolve(new Blob([this._bodyText])) + } + } + + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + return consumed(this) || Promise.resolve(this._bodyArrayBuffer) + } else { + return this.blob().then(readBlobAsArrayBuffer) + } + } + } + + this.text = function() { + var rejected = consumed(this) + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as text') + } else { + return Promise.resolve(this._bodyText) + } + } + + if (support.formData) { + this.formData = function() { + return this.text().then(decode) + } + } + + this.json = function() { + return this.text().then(JSON.parse) + } + + return this + } + + // HTTP methods whose capitalization should be normalized + var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] + + function normalizeMethod(method) { + var upcased = method.toUpperCase() + return (methods.indexOf(upcased) > -1) ? upcased : method + } + + function Request(input, options) { + options = options || {} + var body = options.body + + if (input instanceof Request) { + if (input.bodyUsed) { + throw new TypeError('Already read') + } + this.url = input.url + this.credentials = input.credentials + if (!options.headers) { + this.headers = new Headers(input.headers) + } + this.method = input.method + this.mode = input.mode + if (!body && input._bodyInit != null) { + body = input._bodyInit + input.bodyUsed = true + } + } else { + this.url = String(input) + } + + this.credentials = options.credentials || this.credentials || 'omit' + if (options.headers || !this.headers) { + this.headers = new Headers(options.headers) + } + this.method = normalizeMethod(options.method || this.method || 'GET') + this.mode = options.mode || this.mode || null + this.referrer = null + + if ((this.method === 'GET' || this.method === 'HEAD') && body) { + throw new TypeError('Body not allowed for GET or HEAD requests') + } + this._initBody(body) + } + + Request.prototype.clone = function() { + return new Request(this, { body: this._bodyInit }) + } + + function decode(body) { + var form = new FormData() + body.trim().split('&').forEach(function(bytes) { + if (bytes) { + var split = bytes.split('=') + var name = split.shift().replace(/\+/g, ' ') + var value = split.join('=').replace(/\+/g, ' ') + form.append(decodeURIComponent(name), decodeURIComponent(value)) + } + }) + return form + } + + function parseHeaders(rawHeaders) { + var headers = new Headers() + rawHeaders.split(/\r?\n/).forEach(function(line) { + var parts = line.split(':') + var key = parts.shift().trim() + if (key) { + var value = parts.join(':').trim() + headers.append(key, value) + } + }) + return headers + } + + Body.call(Request.prototype) + + function Response(bodyInit, options) { + if (!options) { + options = {} + } + + this.type = 'default' + this.status = 'status' in options ? options.status : 200 + this.ok = this.status >= 200 && this.status < 300 + this.statusText = 'statusText' in options ? options.statusText : 'OK' + this.headers = new Headers(options.headers) + this.url = options.url || '' + this._initBody(bodyInit) + } + + Body.call(Response.prototype) + + Response.prototype.clone = function() { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers(this.headers), + url: this.url + }) + } + + Response.error = function() { + var response = new Response(null, {status: 0, statusText: ''}) + response.type = 'error' + return response + } + + var redirectStatuses = [301, 302, 303, 307, 308] + + Response.redirect = function(url, status) { + if (redirectStatuses.indexOf(status) === -1) { + throw new RangeError('Invalid status code') + } + + return new Response(null, {status: status, headers: {location: url}}) + } + + self.Headers = Headers + self.Request = Request + self.Response = Response + + self.fetch = function(input, init) { + return new Promise(function(resolve, reject) { + var request = new Request(input, init) + var xhr = new XMLHttpRequest() + + xhr.onload = function() { + var options = { + status: xhr.status, + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || '') + } + options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL') + var body = 'response' in xhr ? xhr.response : xhr.responseText + resolve(new Response(body, options)) + } + + xhr.onerror = function() { + reject(new TypeError('Network request failed')) + } + + xhr.ontimeout = function() { + reject(new TypeError('Network request failed')) + } + + xhr.open(request.method, request.url, true) + + if (request.credentials === 'include') { + xhr.withCredentials = true + } + + if ('responseType' in xhr && support.blob) { + xhr.responseType = 'blob' + } + + request.headers.forEach(function(value, name) { + xhr.setRequestHeader(name, value) + }) + + xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit) + }) + } + self.fetch.polyfill = true +})(typeof self !== 'undefined' ? self : this); + + +/***/ }), + +/***/ 94: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +// Use the fastest means possible to execute a task in its own turn, with +// priority over other events including IO, animation, reflow, and redraw +// events in browsers. +// +// An exception thrown by a task will permanently interrupt the processing of +// subsequent tasks. The higher level `asap` function ensures that if an +// exception is thrown by a task, that the task queue will continue flushing as +// soon as possible, but if you use `rawAsap` directly, you are responsible to +// either ensure that no exceptions are thrown from your task, or to manually +// call `rawAsap.requestFlush` if an exception is thrown. +module.exports = rawAsap; +function rawAsap(task) { + if (!queue.length) { + requestFlush(); + flushing = true; + } + // Equivalent to push, but avoids a function call. + queue[queue.length] = task; +} + +var queue = []; +// Once a flush has been requested, no further calls to `requestFlush` are +// necessary until the next `flush` completes. +var flushing = false; +// `requestFlush` is an implementation-specific method that attempts to kick +// off a `flush` event as quickly as possible. `flush` will attempt to exhaust +// the event queue before yielding to the browser's own event loop. +var requestFlush; +// The position of the next task to execute in the task queue. This is +// preserved between calls to `flush` so that it can be resumed if +// a task throws an exception. +var index = 0; +// If a task schedules additional tasks recursively, the task queue can grow +// unbounded. To prevent memory exhaustion, the task queue will periodically +// truncate already-completed tasks. +var capacity = 1024; + +// The flush function processes all tasks that have been scheduled with +// `rawAsap` unless and until one of those tasks throws an exception. +// If a task throws an exception, `flush` ensures that its state will remain +// consistent and will resume where it left off when called again. +// However, `flush` does not make any arrangements to be called again if an +// exception is thrown. +function flush() { + while (index < queue.length) { + var currentIndex = index; + // Advance the index before calling the task. This ensures that we will + // begin flushing on the next task the task throws an error. + index = index + 1; + queue[currentIndex].call(); + // Prevent leaking memory for long chains of recursive calls to `asap`. + // If we call `asap` within tasks scheduled by `asap`, the queue will + // grow, but to avoid an O(n) walk for every task we execute, we don't + // shift tasks off the queue after they have been executed. + // Instead, we periodically shift 1024 tasks off the queue. + if (index > capacity) { + // Manually shift all values starting at the index back to the + // beginning of the queue. + for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { + queue[scan] = queue[scan + index]; + } + queue.length -= index; + index = 0; + } + } + queue.length = 0; + index = 0; + flushing = false; +} + +// `requestFlush` is implemented using a strategy based on data collected from +// every available SauceLabs Selenium web driver worker at time of writing. +// https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593 + +// Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that +// have WebKitMutationObserver but not un-prefixed MutationObserver. +// Must use `global` or `self` instead of `window` to work in both frames and web +// workers. `global` is a provision of Browserify, Mr, Mrs, or Mop. + +/* globals self */ +var scope = typeof global !== "undefined" ? global : self; +var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver; + +// MutationObservers are desirable because they have high priority and work +// reliably everywhere they are implemented. +// They are implemented in all modern browsers. +// +// - Android 4-4.3 +// - Chrome 26-34 +// - Firefox 14-29 +// - Internet Explorer 11 +// - iPad Safari 6-7.1 +// - iPhone Safari 7-7.1 +// - Safari 6-7 +if (typeof BrowserMutationObserver === "function") { + requestFlush = makeRequestCallFromMutationObserver(flush); + +// MessageChannels are desirable because they give direct access to the HTML +// task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera +// 11-12, and in web workers in many engines. +// Although message channels yield to any queued rendering and IO tasks, they +// would be better than imposing the 4ms delay of timers. +// However, they do not work reliably in Internet Explorer or Safari. + +// Internet Explorer 10 is the only browser that has setImmediate but does +// not have MutationObservers. +// Although setImmediate yields to the browser's renderer, it would be +// preferrable to falling back to setTimeout since it does not have +// the minimum 4ms penalty. +// Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and +// Desktop to a lesser extent) that renders both setImmediate and +// MessageChannel useless for the purposes of ASAP. +// https://github.com/kriskowal/q/issues/396 + +// Timers are implemented universally. +// We fall back to timers in workers in most engines, and in foreground +// contexts in the following browsers. +// However, note that even this simple case requires nuances to operate in a +// broad spectrum of browsers. +// +// - Firefox 3-13 +// - Internet Explorer 6-9 +// - iPad Safari 4.3 +// - Lynx 2.8.7 +} else { + requestFlush = makeRequestCallFromTimer(flush); +} + +// `requestFlush` requests that the high priority event queue be flushed as +// soon as possible. +// This is useful to prevent an error thrown in a task from stalling the event +// queue if the exception handled by Node.js’s +// `process.on("uncaughtException")` or by a domain. +rawAsap.requestFlush = requestFlush; + +// To request a high priority event, we induce a mutation observer by toggling +// the text of a text node between "1" and "-1". +function makeRequestCallFromMutationObserver(callback) { + var toggle = 1; + var observer = new BrowserMutationObserver(callback); + var node = document.createTextNode(""); + observer.observe(node, {characterData: true}); + return function requestCall() { + toggle = -toggle; + node.data = toggle; + }; +} + +// The message channel technique was discovered by Malte Ubl and was the +// original foundation for this library. +// http://www.nonblocking.io/2011/06/windownexttick.html + +// Safari 6.0.5 (at least) intermittently fails to create message ports on a +// page's first load. Thankfully, this version of Safari supports +// MutationObservers, so we don't need to fall back in that case. + +// function makeRequestCallFromMessageChannel(callback) { +// var channel = new MessageChannel(); +// channel.port1.onmessage = callback; +// return function requestCall() { +// channel.port2.postMessage(0); +// }; +// } + +// For reasons explained above, we are also unable to use `setImmediate` +// under any circumstances. +// Even if we were, there is another bug in Internet Explorer 10. +// It is not sufficient to assign `setImmediate` to `requestFlush` because +// `setImmediate` must be called *by name* and therefore must be wrapped in a +// closure. +// Never forget. + +// function makeRequestCallFromSetImmediate(callback) { +// return function requestCall() { +// setImmediate(callback); +// }; +// } + +// Safari 6.0 has a problem where timers will get lost while the user is +// scrolling. This problem does not impact ASAP because Safari 6.0 supports +// mutation observers, so that implementation is used instead. +// However, if we ever elect to use timers in Safari, the prevalent work-around +// is to add a scroll event listener that calls for a flush. + +// `setTimeout` does not call the passed callback if the delay is less than +// approximately 7 in web workers in Firefox 8 through 18, and sometimes not +// even then. + +function makeRequestCallFromTimer(callback) { + return function requestCall() { + // We dispatch a timeout with a specified delay of 0 for engines that + // can reliably accommodate that request. This will usually be snapped + // to a 4 milisecond delay, but once we're flushing, there's no delay + // between events. + var timeoutHandle = setTimeout(handleTimer, 0); + // However, since this timer gets frequently dropped in Firefox + // workers, we enlist an interval handle that will try to fire + // an event 20 times per second until it succeeds. + var intervalHandle = setInterval(handleTimer, 50); + + function handleTimer() { + // Whichever timer succeeds will cancel both timers and + // execute the callback. + clearTimeout(timeoutHandle); + clearInterval(intervalHandle); + callback(); + } + }; +} + +// This is for `asap.js` only. +// Its name will be periodically randomized to break any code that depends on +// its existence. +rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; + +// ASAP was originally a nextTick shim included in Q. This was factored out +// into this ASAP package. It was later adapted to RSVP which made further +// amendments. These decisions, particularly to marginalize MessageChannel and +// to capture the MutationObserver implementation in a closure, were integrated +// back into ASAP proper. +// https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) + +/***/ }), + +/***/ 96: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * This file is automatically included in the JS bundle. + * Don't import it manually. + */ + +if (typeof Promise === 'undefined') { + // Rejection tracking prevents a common issue where React gets into an + // inconsistent state due to an error, but it gets swallowed by a Promise, + // and the user has no idea what causes React's erratic future behavior. + /* eslint-disable global-require */ + __webpack_require__(92).enable(); + window.Promise = __webpack_require__(91); + /* eslint-enable */ +} + +// fetch() polyfill for making API calls. +// Uncomment this line to use fetch in your code. +// It is left out by default, because the polyfill is big. +__webpack_require__(93); + +/* eslint-disable */ +// https://tc39.github.io/ecma262/#sec-array.prototype.find +if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { + value: function value(predicate) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If IsCallable(predicate) is false, throw a TypeError exception. + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + + // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. + var thisArg = arguments[1]; + + // 5. Let k be 0. + var k = 0; + + // 6. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kValue be ? Get(O, Pk). + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). + // d. If testResult is true, return kValue. + var kValue = o[k]; + if (predicate.call(thisArg, kValue, k, o)) { + return kValue; + } + // e. Increase k by 1. + k++; + } + + // 7. Return undefined. + return undefined; + } + }); +} +/* eslint-enable */ + +/***/ }) + +/******/ }); \ No newline at end of file diff --git a/wagtailmodelchoosers/static/wagtailmodelchoosers/wagtailmodelchoosers.css b/wagtailmodelchoosers/static/wagtailmodelchoosers/wagtailmodelchoosers.css new file mode 100644 index 0000000..c4ca152 --- /dev/null +++ b/wagtailmodelchoosers/static/wagtailmodelchoosers/wagtailmodelchoosers.css @@ -0,0 +1,246 @@ +/* ========================================================================== *\ + Wagtail Model Chooser CSS +\* ========================================================================== */ + +.admin-modal { + position: fixed; + display: flex; + align-items: center; + justify-content: center; + z-index: 1300; + overflow-x: hidden; + overflow-y: hidden; +} + +.admin-modal__header { + padding: 1rem; + background: #374646; +} + + +.admin-modal__header h2 { + color: #fff; + margin: 0; +} + +.admin-modal__content { + background-color: #fff; + overflow-y: auto; + flex: 1; +} + +.admin-modal__dialog { + position: relative; + display: flex; + flex-direction: column; + max-width: 80%; + max-width: 60%; + margin-left: auto; + margin-right: auto; + border-radius: 3px; + overflow: hidden; + box-shadow: 0 2px 5px rgba(0,0,0,0.2); + animation: dialogIn .35s cubic-bezier(0.075, 0.82, 0.165, 1) .2s backwards; + height: 65%; +} + +@media only screen and (min-width: 50rem) { + .admin-modal__dialog { + min-width: 70%; + } +} + +.admin-modal--exit .admin-modal__dialog { + animation: dialogOut .3s ease forwards; +} + +.admin-modal--exit.admin-modal:before { + animation: dialogFadeOut .3s ease .35s forwards; +} + + +.chooser-table { + width: 100%; + table-layout: fixed; +} + + +.chooser-table thead { + background: #E9EAEA; +} + +.chooser-table thead td { + padding: .75rem 1rem; +} + + +.chooser__item:last-child > .chooser__cell { + border-bottom-width: 0; +} + +.chooser__item:hover { + background: #666; + cursor: pointer; + color: #fff; +} + +.chooser__item:hover a { + color: #fff; +} + +.chooser__cell { + padding: .75rem 1rem; + border-bottom: solid 1px #eee; +} + + +.admin-modal:before { + content: ''; + position: absolute; + width: 100%; + height: 100%; + top: 0; + left: 0; + background: rgba(0, 0, 0, 0.4); + animation: dialogFadeIn .2s ease backwards; +} + + +.admin-modal__actions { + overflow: hidden; + bottom: 0; + left: 0; + right: 0; + padding: .75rem 1rem; + background: #f5f5f5; +} + +.admin-modal__action { + float: left; + width: 50%; + margin-bottom: 0; +} + +.admin-modal__action input[type='text'] { + padding: .5em; + background: #fff; + border-color: #ccc; + box-shadow: 0 1px 2px rgba(0,0,0,0.05); +} + + +.admin-modal__action:last-child { + /*padding-top: .5rem;*/ +} + +.admin-modal__pagination { + margin-right: 1.5rem; + display: inline-block; +} + +.admin-modal__results { + display: inline-block; + margin-right: 1.5rem; +} + + +.admin-modal__action > p { + margin-top: .5rem; + margin-bottom: 0; +} + +.admin-modal__action:last-child { + text-align: right; +} + + + +.struct-block .model-chooser { + padding: 1rem 0; +} + +.model-chooser__label:not(:empty) { + margin-right: .5rem; + display: inline-block; + +} + +.model-chooser__label:not(:empty) { + width: 9rem; + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +.model-chooser__label + span { + display: inline-block; + vertical-align: top; +} + + +.button--disabled { + pointer-events: none; + opacity: .7; + background: rgba(0,0,0,0.4); + border-color: rgba(0,0,0,0.25); + color: #ddd; +} + + +/* ========================================================================== *\ + Animations +\* ========================================================================== */ + + +@keyframes dialogIn { + 0% { + opacity: 0; + transform: translateY(20%); + } + + 100% { + opacity: 1; + transform: translateY(0%); + } +} + + +@keyframes dialogOut { + 0% { + opacity: 1; + transform: translateY(0%); + } + 100% { + opacity: 0; + transform: translateY(20%); + } +} + +@keyframes dialogFadeIn { + 0% { + opacity: 0; + } + 100% { + opacity: 1; + } +} + + +@keyframes dialogFadeOut { + 0% { + opacity: 1; + } + 100% { + opacity: 0; + } +} + +/* ========================================================================== *\ + Shame +\* ========================================================================== */ + +/* Overwrite for https://github.com/wagtail/wagtail/blob/3923ee668c292ed2d1d2e76ae1a728da20b9be68 +/wagtail/wagtailadmin/static_src/wagtailadmin/scss/layouts/page-editor.scss#L305 */ +.object.collapsible .admin-modal__header h2:before { + content: ''; +} diff --git a/wagtailmodelchoosers/static/wagtailmodelchoosers/wagtailmodelchoosers.js b/wagtailmodelchoosers/static/wagtailmodelchoosers/wagtailmodelchoosers.js new file mode 100644 index 0000000..551e41c --- /dev/null +++ b/wagtailmodelchoosers/static/wagtailmodelchoosers/wagtailmodelchoosers.js @@ -0,0 +1,45732 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 97); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports) { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Copyright (c) 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +(function (global, factory) { + true ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + global.Immutable = factory(); +}(this, function () { 'use strict';var SLICE$0 = Array.prototype.slice; + + function createClass(ctor, superClass) { + if (superClass) { + ctor.prototype = Object.create(superClass.prototype); + } + ctor.prototype.constructor = ctor; + } + + function Iterable(value) { + return isIterable(value) ? value : Seq(value); + } + + + createClass(KeyedIterable, Iterable); + function KeyedIterable(value) { + return isKeyed(value) ? value : KeyedSeq(value); + } + + + createClass(IndexedIterable, Iterable); + function IndexedIterable(value) { + return isIndexed(value) ? value : IndexedSeq(value); + } + + + createClass(SetIterable, Iterable); + function SetIterable(value) { + return isIterable(value) && !isAssociative(value) ? value : SetSeq(value); + } + + + + function isIterable(maybeIterable) { + return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]); + } + + function isKeyed(maybeKeyed) { + return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]); + } + + function isIndexed(maybeIndexed) { + return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]); + } + + function isAssociative(maybeAssociative) { + return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); + } + + function isOrdered(maybeOrdered) { + return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]); + } + + Iterable.isIterable = isIterable; + Iterable.isKeyed = isKeyed; + Iterable.isIndexed = isIndexed; + Iterable.isAssociative = isAssociative; + Iterable.isOrdered = isOrdered; + + Iterable.Keyed = KeyedIterable; + Iterable.Indexed = IndexedIterable; + Iterable.Set = SetIterable; + + + var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; + var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; + var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; + var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; + + // Used for setting prototype methods that IE8 chokes on. + var DELETE = 'delete'; + + // Constants describing the size of trie nodes. + var SHIFT = 5; // Resulted in best performance after ______? + var SIZE = 1 << SHIFT; + var MASK = SIZE - 1; + + // A consistent shared value representing "not set" which equals nothing other + // than itself, and nothing that could be provided externally. + var NOT_SET = {}; + + // Boolean references, Rough equivalent of `bool &`. + var CHANGE_LENGTH = { value: false }; + var DID_ALTER = { value: false }; + + function MakeRef(ref) { + ref.value = false; + return ref; + } + + function SetRef(ref) { + ref && (ref.value = true); + } + + // A function which returns a value representing an "owner" for transient writes + // to tries. The return value will only ever equal itself, and will not equal + // the return of any subsequent call of this function. + function OwnerID() {} + + // http://jsperf.com/copy-array-inline + function arrCopy(arr, offset) { + offset = offset || 0; + var len = Math.max(0, arr.length - offset); + var newArr = new Array(len); + for (var ii = 0; ii < len; ii++) { + newArr[ii] = arr[ii + offset]; + } + return newArr; + } + + function ensureSize(iter) { + if (iter.size === undefined) { + iter.size = iter.__iterate(returnTrue); + } + return iter.size; + } + + function wrapIndex(iter, index) { + // This implements "is array index" which the ECMAString spec defines as: + // + // A String property name P is an array index if and only if + // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal + // to 2^32−1. + // + // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects + if (typeof index !== 'number') { + var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 + if ('' + uint32Index !== index || uint32Index === 4294967295) { + return NaN; + } + index = uint32Index; + } + return index < 0 ? ensureSize(iter) + index : index; + } + + function returnTrue() { + return true; + } + + function wholeSlice(begin, end, size) { + return (begin === 0 || (size !== undefined && begin <= -size)) && + (end === undefined || (size !== undefined && end >= size)); + } + + function resolveBegin(begin, size) { + return resolveIndex(begin, size, 0); + } + + function resolveEnd(end, size) { + return resolveIndex(end, size, size); + } + + function resolveIndex(index, size, defaultIndex) { + return index === undefined ? + defaultIndex : + index < 0 ? + Math.max(0, size + index) : + size === undefined ? + index : + Math.min(size, index); + } + + /* global Symbol */ + + var ITERATE_KEYS = 0; + var ITERATE_VALUES = 1; + var ITERATE_ENTRIES = 2; + + var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; + + var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; + + + function Iterator(next) { + this.next = next; + } + + Iterator.prototype.toString = function() { + return '[Iterator]'; + }; + + + Iterator.KEYS = ITERATE_KEYS; + Iterator.VALUES = ITERATE_VALUES; + Iterator.ENTRIES = ITERATE_ENTRIES; + + Iterator.prototype.inspect = + Iterator.prototype.toSource = function () { return this.toString(); } + Iterator.prototype[ITERATOR_SYMBOL] = function () { + return this; + }; + + + function iteratorValue(type, k, v, iteratorResult) { + var value = type === 0 ? k : type === 1 ? v : [k, v]; + iteratorResult ? (iteratorResult.value = value) : (iteratorResult = { + value: value, done: false + }); + return iteratorResult; + } + + function iteratorDone() { + return { value: undefined, done: true }; + } + + function hasIterator(maybeIterable) { + return !!getIteratorFn(maybeIterable); + } + + function isIterator(maybeIterator) { + return maybeIterator && typeof maybeIterator.next === 'function'; + } + + function getIterator(iterable) { + var iteratorFn = getIteratorFn(iterable); + return iteratorFn && iteratorFn.call(iterable); + } + + function getIteratorFn(iterable) { + var iteratorFn = iterable && ( + (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || + iterable[FAUX_ITERATOR_SYMBOL] + ); + if (typeof iteratorFn === 'function') { + return iteratorFn; + } + } + + function isArrayLike(value) { + return value && typeof value.length === 'number'; + } + + createClass(Seq, Iterable); + function Seq(value) { + return value === null || value === undefined ? emptySequence() : + isIterable(value) ? value.toSeq() : seqFromValue(value); + } + + Seq.of = function(/*...values*/) { + return Seq(arguments); + }; + + Seq.prototype.toSeq = function() { + return this; + }; + + Seq.prototype.toString = function() { + return this.__toString('Seq {', '}'); + }; + + Seq.prototype.cacheResult = function() { + if (!this._cache && this.__iterateUncached) { + this._cache = this.entrySeq().toArray(); + this.size = this._cache.length; + } + return this; + }; + + // abstract __iterateUncached(fn, reverse) + + Seq.prototype.__iterate = function(fn, reverse) { + return seqIterate(this, fn, reverse, true); + }; + + // abstract __iteratorUncached(type, reverse) + + Seq.prototype.__iterator = function(type, reverse) { + return seqIterator(this, type, reverse, true); + }; + + + + createClass(KeyedSeq, Seq); + function KeyedSeq(value) { + return value === null || value === undefined ? + emptySequence().toKeyedSeq() : + isIterable(value) ? + (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) : + keyedSeqFromValue(value); + } + + KeyedSeq.prototype.toKeyedSeq = function() { + return this; + }; + + + + createClass(IndexedSeq, Seq); + function IndexedSeq(value) { + return value === null || value === undefined ? emptySequence() : + !isIterable(value) ? indexedSeqFromValue(value) : + isKeyed(value) ? value.entrySeq() : value.toIndexedSeq(); + } + + IndexedSeq.of = function(/*...values*/) { + return IndexedSeq(arguments); + }; + + IndexedSeq.prototype.toIndexedSeq = function() { + return this; + }; + + IndexedSeq.prototype.toString = function() { + return this.__toString('Seq [', ']'); + }; + + IndexedSeq.prototype.__iterate = function(fn, reverse) { + return seqIterate(this, fn, reverse, false); + }; + + IndexedSeq.prototype.__iterator = function(type, reverse) { + return seqIterator(this, type, reverse, false); + }; + + + + createClass(SetSeq, Seq); + function SetSeq(value) { + return ( + value === null || value === undefined ? emptySequence() : + !isIterable(value) ? indexedSeqFromValue(value) : + isKeyed(value) ? value.entrySeq() : value + ).toSetSeq(); + } + + SetSeq.of = function(/*...values*/) { + return SetSeq(arguments); + }; + + SetSeq.prototype.toSetSeq = function() { + return this; + }; + + + + Seq.isSeq = isSeq; + Seq.Keyed = KeyedSeq; + Seq.Set = SetSeq; + Seq.Indexed = IndexedSeq; + + var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; + + Seq.prototype[IS_SEQ_SENTINEL] = true; + + + + createClass(ArraySeq, IndexedSeq); + function ArraySeq(array) { + this._array = array; + this.size = array.length; + } + + ArraySeq.prototype.get = function(index, notSetValue) { + return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; + }; + + ArraySeq.prototype.__iterate = function(fn, reverse) { + var array = this._array; + var maxIndex = array.length - 1; + for (var ii = 0; ii <= maxIndex; ii++) { + if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) { + return ii + 1; + } + } + return ii; + }; + + ArraySeq.prototype.__iterator = function(type, reverse) { + var array = this._array; + var maxIndex = array.length - 1; + var ii = 0; + return new Iterator(function() + {return ii > maxIndex ? + iteratorDone() : + iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])} + ); + }; + + + + createClass(ObjectSeq, KeyedSeq); + function ObjectSeq(object) { + var keys = Object.keys(object); + this._object = object; + this._keys = keys; + this.size = keys.length; + } + + ObjectSeq.prototype.get = function(key, notSetValue) { + if (notSetValue !== undefined && !this.has(key)) { + return notSetValue; + } + return this._object[key]; + }; + + ObjectSeq.prototype.has = function(key) { + return this._object.hasOwnProperty(key); + }; + + ObjectSeq.prototype.__iterate = function(fn, reverse) { + var object = this._object; + var keys = this._keys; + var maxIndex = keys.length - 1; + for (var ii = 0; ii <= maxIndex; ii++) { + var key = keys[reverse ? maxIndex - ii : ii]; + if (fn(object[key], key, this) === false) { + return ii + 1; + } + } + return ii; + }; + + ObjectSeq.prototype.__iterator = function(type, reverse) { + var object = this._object; + var keys = this._keys; + var maxIndex = keys.length - 1; + var ii = 0; + return new Iterator(function() { + var key = keys[reverse ? maxIndex - ii : ii]; + return ii++ > maxIndex ? + iteratorDone() : + iteratorValue(type, key, object[key]); + }); + }; + + ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true; + + + createClass(IterableSeq, IndexedSeq); + function IterableSeq(iterable) { + this._iterable = iterable; + this.size = iterable.length || iterable.size; + } + + IterableSeq.prototype.__iterateUncached = function(fn, reverse) { + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var iterable = this._iterable; + var iterator = getIterator(iterable); + var iterations = 0; + if (isIterator(iterator)) { + var step; + while (!(step = iterator.next()).done) { + if (fn(step.value, iterations++, this) === false) { + break; + } + } + } + return iterations; + }; + + IterableSeq.prototype.__iteratorUncached = function(type, reverse) { + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterable = this._iterable; + var iterator = getIterator(iterable); + if (!isIterator(iterator)) { + return new Iterator(iteratorDone); + } + var iterations = 0; + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : iteratorValue(type, iterations++, step.value); + }); + }; + + + + createClass(IteratorSeq, IndexedSeq); + function IteratorSeq(iterator) { + this._iterator = iterator; + this._iteratorCache = []; + } + + IteratorSeq.prototype.__iterateUncached = function(fn, reverse) { + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var iterator = this._iterator; + var cache = this._iteratorCache; + var iterations = 0; + while (iterations < cache.length) { + if (fn(cache[iterations], iterations++, this) === false) { + return iterations; + } + } + var step; + while (!(step = iterator.next()).done) { + var val = step.value; + cache[iterations] = val; + if (fn(val, iterations++, this) === false) { + break; + } + } + return iterations; + }; + + IteratorSeq.prototype.__iteratorUncached = function(type, reverse) { + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = this._iterator; + var cache = this._iteratorCache; + var iterations = 0; + return new Iterator(function() { + if (iterations >= cache.length) { + var step = iterator.next(); + if (step.done) { + return step; + } + cache[iterations] = step.value; + } + return iteratorValue(type, iterations, cache[iterations++]); + }); + }; + + + + + // # pragma Helper functions + + function isSeq(maybeSeq) { + return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]); + } + + var EMPTY_SEQ; + + function emptySequence() { + return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); + } + + function keyedSeqFromValue(value) { + var seq = + Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() : + isIterator(value) ? new IteratorSeq(value).fromEntrySeq() : + hasIterator(value) ? new IterableSeq(value).fromEntrySeq() : + typeof value === 'object' ? new ObjectSeq(value) : + undefined; + if (!seq) { + throw new TypeError( + 'Expected Array or iterable object of [k, v] entries, '+ + 'or keyed object: ' + value + ); + } + return seq; + } + + function indexedSeqFromValue(value) { + var seq = maybeIndexedSeqFromValue(value); + if (!seq) { + throw new TypeError( + 'Expected Array or iterable object of values: ' + value + ); + } + return seq; + } + + function seqFromValue(value) { + var seq = maybeIndexedSeqFromValue(value) || + (typeof value === 'object' && new ObjectSeq(value)); + if (!seq) { + throw new TypeError( + 'Expected Array or iterable object of values, or keyed object: ' + value + ); + } + return seq; + } + + function maybeIndexedSeqFromValue(value) { + return ( + isArrayLike(value) ? new ArraySeq(value) : + isIterator(value) ? new IteratorSeq(value) : + hasIterator(value) ? new IterableSeq(value) : + undefined + ); + } + + function seqIterate(seq, fn, reverse, useKeys) { + var cache = seq._cache; + if (cache) { + var maxIndex = cache.length - 1; + for (var ii = 0; ii <= maxIndex; ii++) { + var entry = cache[reverse ? maxIndex - ii : ii]; + if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) { + return ii + 1; + } + } + return ii; + } + return seq.__iterateUncached(fn, reverse); + } + + function seqIterator(seq, type, reverse, useKeys) { + var cache = seq._cache; + if (cache) { + var maxIndex = cache.length - 1; + var ii = 0; + return new Iterator(function() { + var entry = cache[reverse ? maxIndex - ii : ii]; + return ii++ > maxIndex ? + iteratorDone() : + iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]); + }); + } + return seq.__iteratorUncached(type, reverse); + } + + function fromJS(json, converter) { + return converter ? + fromJSWith(converter, json, '', {'': json}) : + fromJSDefault(json); + } + + function fromJSWith(converter, json, key, parentJSON) { + if (Array.isArray(json)) { + return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); + } + if (isPlainObj(json)) { + return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); + } + return json; + } + + function fromJSDefault(json) { + if (Array.isArray(json)) { + return IndexedSeq(json).map(fromJSDefault).toList(); + } + if (isPlainObj(json)) { + return KeyedSeq(json).map(fromJSDefault).toMap(); + } + return json; + } + + function isPlainObj(value) { + return value && (value.constructor === Object || value.constructor === undefined); + } + + /** + * An extension of the "same-value" algorithm as [described for use by ES6 Map + * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) + * + * NaN is considered the same as NaN, however -0 and 0 are considered the same + * value, which is different from the algorithm described by + * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * This is extended further to allow Objects to describe the values they + * represent, by way of `valueOf` or `equals` (and `hashCode`). + * + * Note: because of this extension, the key equality of Immutable.Map and the + * value equality of Immutable.Set will differ from ES6 Map and Set. + * + * ### Defining custom values + * + * The easiest way to describe the value an object represents is by implementing + * `valueOf`. For example, `Date` represents a value by returning a unix + * timestamp for `valueOf`: + * + * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... + * var date2 = new Date(1234567890000); + * date1.valueOf(); // 1234567890000 + * assert( date1 !== date2 ); + * assert( Immutable.is( date1, date2 ) ); + * + * Note: overriding `valueOf` may have other implications if you use this object + * where JavaScript expects a primitive, such as implicit string coercion. + * + * For more complex types, especially collections, implementing `valueOf` may + * not be performant. An alternative is to implement `equals` and `hashCode`. + * + * `equals` takes another object, presumably of similar type, and returns true + * if the it is equal. Equality is symmetrical, so the same result should be + * returned if this and the argument are flipped. + * + * assert( a.equals(b) === b.equals(a) ); + * + * `hashCode` returns a 32bit integer number representing the object which will + * be used to determine how to store the value object in a Map or Set. You must + * provide both or neither methods, one must not exist without the other. + * + * Also, an important relationship between these methods must be upheld: if two + * values are equal, they *must* return the same hashCode. If the values are not + * equal, they might have the same hashCode; this is called a hash collision, + * and while undesirable for performance reasons, it is acceptable. + * + * if (a.equals(b)) { + * assert( a.hashCode() === b.hashCode() ); + * } + * + * All Immutable collections implement `equals` and `hashCode`. + * + */ + function is(valueA, valueB) { + if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { + return true; + } + if (!valueA || !valueB) { + return false; + } + if (typeof valueA.valueOf === 'function' && + typeof valueB.valueOf === 'function') { + valueA = valueA.valueOf(); + valueB = valueB.valueOf(); + if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { + return true; + } + if (!valueA || !valueB) { + return false; + } + } + if (typeof valueA.equals === 'function' && + typeof valueB.equals === 'function' && + valueA.equals(valueB)) { + return true; + } + return false; + } + + function deepEqual(a, b) { + if (a === b) { + return true; + } + + if ( + !isIterable(b) || + a.size !== undefined && b.size !== undefined && a.size !== b.size || + a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash || + isKeyed(a) !== isKeyed(b) || + isIndexed(a) !== isIndexed(b) || + isOrdered(a) !== isOrdered(b) + ) { + return false; + } + + if (a.size === 0 && b.size === 0) { + return true; + } + + var notAssociative = !isAssociative(a); + + if (isOrdered(a)) { + var entries = a.entries(); + return b.every(function(v, k) { + var entry = entries.next().value; + return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); + }) && entries.next().done; + } + + var flipped = false; + + if (a.size === undefined) { + if (b.size === undefined) { + if (typeof a.cacheResult === 'function') { + a.cacheResult(); + } + } else { + flipped = true; + var _ = a; + a = b; + b = _; + } + } + + var allEqual = true; + var bSize = b.__iterate(function(v, k) { + if (notAssociative ? !a.has(v) : + flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) { + allEqual = false; + return false; + } + }); + + return allEqual && a.size === bSize; + } + + createClass(Repeat, IndexedSeq); + + function Repeat(value, times) { + if (!(this instanceof Repeat)) { + return new Repeat(value, times); + } + this._value = value; + this.size = times === undefined ? Infinity : Math.max(0, times); + if (this.size === 0) { + if (EMPTY_REPEAT) { + return EMPTY_REPEAT; + } + EMPTY_REPEAT = this; + } + } + + Repeat.prototype.toString = function() { + if (this.size === 0) { + return 'Repeat []'; + } + return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; + }; + + Repeat.prototype.get = function(index, notSetValue) { + return this.has(index) ? this._value : notSetValue; + }; + + Repeat.prototype.includes = function(searchValue) { + return is(this._value, searchValue); + }; + + Repeat.prototype.slice = function(begin, end) { + var size = this.size; + return wholeSlice(begin, end, size) ? this : + new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size)); + }; + + Repeat.prototype.reverse = function() { + return this; + }; + + Repeat.prototype.indexOf = function(searchValue) { + if (is(this._value, searchValue)) { + return 0; + } + return -1; + }; + + Repeat.prototype.lastIndexOf = function(searchValue) { + if (is(this._value, searchValue)) { + return this.size; + } + return -1; + }; + + Repeat.prototype.__iterate = function(fn, reverse) { + for (var ii = 0; ii < this.size; ii++) { + if (fn(this._value, ii, this) === false) { + return ii + 1; + } + } + return ii; + }; + + Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this; + var ii = 0; + return new Iterator(function() + {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()} + ); + }; + + Repeat.prototype.equals = function(other) { + return other instanceof Repeat ? + is(this._value, other._value) : + deepEqual(other); + }; + + + var EMPTY_REPEAT; + + function invariant(condition, error) { + if (!condition) throw new Error(error); + } + + createClass(Range, IndexedSeq); + + function Range(start, end, step) { + if (!(this instanceof Range)) { + return new Range(start, end, step); + } + invariant(step !== 0, 'Cannot step a Range by 0'); + start = start || 0; + if (end === undefined) { + end = Infinity; + } + step = step === undefined ? 1 : Math.abs(step); + if (end < start) { + step = -step; + } + this._start = start; + this._end = end; + this._step = step; + this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); + if (this.size === 0) { + if (EMPTY_RANGE) { + return EMPTY_RANGE; + } + EMPTY_RANGE = this; + } + } + + Range.prototype.toString = function() { + if (this.size === 0) { + return 'Range []'; + } + return 'Range [ ' + + this._start + '...' + this._end + + (this._step > 1 ? ' by ' + this._step : '') + + ' ]'; + }; + + Range.prototype.get = function(index, notSetValue) { + return this.has(index) ? + this._start + wrapIndex(this, index) * this._step : + notSetValue; + }; + + Range.prototype.includes = function(searchValue) { + var possibleIndex = (searchValue - this._start) / this._step; + return possibleIndex >= 0 && + possibleIndex < this.size && + possibleIndex === Math.floor(possibleIndex); + }; + + Range.prototype.slice = function(begin, end) { + if (wholeSlice(begin, end, this.size)) { + return this; + } + begin = resolveBegin(begin, this.size); + end = resolveEnd(end, this.size); + if (end <= begin) { + return new Range(0, 0); + } + return new Range(this.get(begin, this._end), this.get(end, this._end), this._step); + }; + + Range.prototype.indexOf = function(searchValue) { + var offsetValue = searchValue - this._start; + if (offsetValue % this._step === 0) { + var index = offsetValue / this._step; + if (index >= 0 && index < this.size) { + return index + } + } + return -1; + }; + + Range.prototype.lastIndexOf = function(searchValue) { + return this.indexOf(searchValue); + }; + + Range.prototype.__iterate = function(fn, reverse) { + var maxIndex = this.size - 1; + var step = this._step; + var value = reverse ? this._start + maxIndex * step : this._start; + for (var ii = 0; ii <= maxIndex; ii++) { + if (fn(value, ii, this) === false) { + return ii + 1; + } + value += reverse ? -step : step; + } + return ii; + }; + + Range.prototype.__iterator = function(type, reverse) { + var maxIndex = this.size - 1; + var step = this._step; + var value = reverse ? this._start + maxIndex * step : this._start; + var ii = 0; + return new Iterator(function() { + var v = value; + value += reverse ? -step : step; + return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v); + }); + }; + + Range.prototype.equals = function(other) { + return other instanceof Range ? + this._start === other._start && + this._end === other._end && + this._step === other._step : + deepEqual(this, other); + }; + + + var EMPTY_RANGE; + + createClass(Collection, Iterable); + function Collection() { + throw TypeError('Abstract'); + } + + + createClass(KeyedCollection, Collection);function KeyedCollection() {} + + createClass(IndexedCollection, Collection);function IndexedCollection() {} + + createClass(SetCollection, Collection);function SetCollection() {} + + + Collection.Keyed = KeyedCollection; + Collection.Indexed = IndexedCollection; + Collection.Set = SetCollection; + + var imul = + typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ? + Math.imul : + function imul(a, b) { + a = a | 0; // int + b = b | 0; // int + var c = a & 0xffff; + var d = b & 0xffff; + // Shift by 0 fixes the sign on the high part. + return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int + }; + + // v8 has an optimization for storing 31-bit signed numbers. + // Values which have either 00 or 11 as the high order bits qualify. + // This function drops the highest order bit in a signed number, maintaining + // the sign bit. + function smi(i32) { + return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF); + } + + function hash(o) { + if (o === false || o === null || o === undefined) { + return 0; + } + if (typeof o.valueOf === 'function') { + o = o.valueOf(); + if (o === false || o === null || o === undefined) { + return 0; + } + } + if (o === true) { + return 1; + } + var type = typeof o; + if (type === 'number') { + var h = o | 0; + if (h !== o) { + h ^= o * 0xFFFFFFFF; + } + while (o > 0xFFFFFFFF) { + o /= 0xFFFFFFFF; + h ^= o; + } + return smi(h); + } + if (type === 'string') { + return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o); + } + if (typeof o.hashCode === 'function') { + return o.hashCode(); + } + if (type === 'object') { + return hashJSObj(o); + } + if (typeof o.toString === 'function') { + return hashString(o.toString()); + } + throw new Error('Value type ' + type + ' cannot be hashed.'); + } + + function cachedHashString(string) { + var hash = stringHashCache[string]; + if (hash === undefined) { + hash = hashString(string); + if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { + STRING_HASH_CACHE_SIZE = 0; + stringHashCache = {}; + } + STRING_HASH_CACHE_SIZE++; + stringHashCache[string] = hash; + } + return hash; + } + + // http://jsperf.com/hashing-strings + function hashString(string) { + // This is the hash from JVM + // The hash code for a string is computed as + // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], + // where s[i] is the ith character of the string and n is the length of + // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 + // (exclusive) by dropping high bits. + var hash = 0; + for (var ii = 0; ii < string.length; ii++) { + hash = 31 * hash + string.charCodeAt(ii) | 0; + } + return smi(hash); + } + + function hashJSObj(obj) { + var hash; + if (usingWeakMap) { + hash = weakMap.get(obj); + if (hash !== undefined) { + return hash; + } + } + + hash = obj[UID_HASH_KEY]; + if (hash !== undefined) { + return hash; + } + + if (!canDefineProperty) { + hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; + if (hash !== undefined) { + return hash; + } + + hash = getIENodeHash(obj); + if (hash !== undefined) { + return hash; + } + } + + hash = ++objHashUID; + if (objHashUID & 0x40000000) { + objHashUID = 0; + } + + if (usingWeakMap) { + weakMap.set(obj, hash); + } else if (isExtensible !== undefined && isExtensible(obj) === false) { + throw new Error('Non-extensible objects are not allowed as keys.'); + } else if (canDefineProperty) { + Object.defineProperty(obj, UID_HASH_KEY, { + 'enumerable': false, + 'configurable': false, + 'writable': false, + 'value': hash + }); + } else if (obj.propertyIsEnumerable !== undefined && + obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) { + // Since we can't define a non-enumerable property on the object + // we'll hijack one of the less-used non-enumerable properties to + // save our hash on it. Since this is a function it will not show up in + // `JSON.stringify` which is what we want. + obj.propertyIsEnumerable = function() { + return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments); + }; + obj.propertyIsEnumerable[UID_HASH_KEY] = hash; + } else if (obj.nodeType !== undefined) { + // At this point we couldn't get the IE `uniqueID` to use as a hash + // and we couldn't use a non-enumerable property to exploit the + // dontEnum bug so we simply add the `UID_HASH_KEY` on the node + // itself. + obj[UID_HASH_KEY] = hash; + } else { + throw new Error('Unable to set a non-enumerable property on object.'); + } + + return hash; + } + + // Get references to ES5 object methods. + var isExtensible = Object.isExtensible; + + // True if Object.defineProperty works as expected. IE8 fails this test. + var canDefineProperty = (function() { + try { + Object.defineProperty({}, '@', {}); + return true; + } catch (e) { + return false; + } + }()); + + // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it + // and avoid memory leaks from the IE cloneNode bug. + function getIENodeHash(node) { + if (node && node.nodeType > 0) { + switch (node.nodeType) { + case 1: // Element + return node.uniqueID; + case 9: // Document + return node.documentElement && node.documentElement.uniqueID; + } + } + } + + // If possible, use a WeakMap. + var usingWeakMap = typeof WeakMap === 'function'; + var weakMap; + if (usingWeakMap) { + weakMap = new WeakMap(); + } + + var objHashUID = 0; + + var UID_HASH_KEY = '__immutablehash__'; + if (typeof Symbol === 'function') { + UID_HASH_KEY = Symbol(UID_HASH_KEY); + } + + var STRING_HASH_CACHE_MIN_STRLEN = 16; + var STRING_HASH_CACHE_MAX_SIZE = 255; + var STRING_HASH_CACHE_SIZE = 0; + var stringHashCache = {}; + + function assertNotInfinite(size) { + invariant( + size !== Infinity, + 'Cannot perform this action with an infinite size.' + ); + } + + createClass(Map, KeyedCollection); + + // @pragma Construction + + function Map(value) { + return value === null || value === undefined ? emptyMap() : + isMap(value) && !isOrdered(value) ? value : + emptyMap().withMutations(function(map ) { + var iter = KeyedIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v, k) {return map.set(k, v)}); + }); + } + + Map.prototype.toString = function() { + return this.__toString('Map {', '}'); + }; + + // @pragma Access + + Map.prototype.get = function(k, notSetValue) { + return this._root ? + this._root.get(0, undefined, k, notSetValue) : + notSetValue; + }; + + // @pragma Modification + + Map.prototype.set = function(k, v) { + return updateMap(this, k, v); + }; + + Map.prototype.setIn = function(keyPath, v) { + return this.updateIn(keyPath, NOT_SET, function() {return v}); + }; + + Map.prototype.remove = function(k) { + return updateMap(this, k, NOT_SET); + }; + + Map.prototype.deleteIn = function(keyPath) { + return this.updateIn(keyPath, function() {return NOT_SET}); + }; + + Map.prototype.update = function(k, notSetValue, updater) { + return arguments.length === 1 ? + k(this) : + this.updateIn([k], notSetValue, updater); + }; + + Map.prototype.updateIn = function(keyPath, notSetValue, updater) { + if (!updater) { + updater = notSetValue; + notSetValue = undefined; + } + var updatedValue = updateInDeepMap( + this, + forceIterator(keyPath), + notSetValue, + updater + ); + return updatedValue === NOT_SET ? undefined : updatedValue; + }; + + Map.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._root = null; + this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyMap(); + }; + + // @pragma Composition + + Map.prototype.merge = function(/*...iters*/) { + return mergeIntoMapWith(this, undefined, arguments); + }; + + Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoMapWith(this, merger, iters); + }; + + Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); + return this.updateIn( + keyPath, + emptyMap(), + function(m ) {return typeof m.merge === 'function' ? + m.merge.apply(m, iters) : + iters[iters.length - 1]} + ); + }; + + Map.prototype.mergeDeep = function(/*...iters*/) { + return mergeIntoMapWith(this, deepMerger, arguments); + }; + + Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoMapWith(this, deepMergerWith(merger), iters); + }; + + Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); + return this.updateIn( + keyPath, + emptyMap(), + function(m ) {return typeof m.mergeDeep === 'function' ? + m.mergeDeep.apply(m, iters) : + iters[iters.length - 1]} + ); + }; + + Map.prototype.sort = function(comparator) { + // Late binding + return OrderedMap(sortFactory(this, comparator)); + }; + + Map.prototype.sortBy = function(mapper, comparator) { + // Late binding + return OrderedMap(sortFactory(this, comparator, mapper)); + }; + + // @pragma Mutability + + Map.prototype.withMutations = function(fn) { + var mutable = this.asMutable(); + fn(mutable); + return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; + }; + + Map.prototype.asMutable = function() { + return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); + }; + + Map.prototype.asImmutable = function() { + return this.__ensureOwner(); + }; + + Map.prototype.wasAltered = function() { + return this.__altered; + }; + + Map.prototype.__iterator = function(type, reverse) { + return new MapIterator(this, type, reverse); + }; + + Map.prototype.__iterate = function(fn, reverse) {var this$0 = this; + var iterations = 0; + this._root && this._root.iterate(function(entry ) { + iterations++; + return fn(entry[1], entry[0], this$0); + }, reverse); + return iterations; + }; + + Map.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + this.__ownerID = ownerID; + this.__altered = false; + return this; + } + return makeMap(this.size, this._root, ownerID, this.__hash); + }; + + + function isMap(maybeMap) { + return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]); + } + + Map.isMap = isMap; + + var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; + + var MapPrototype = Map.prototype; + MapPrototype[IS_MAP_SENTINEL] = true; + MapPrototype[DELETE] = MapPrototype.remove; + MapPrototype.removeIn = MapPrototype.deleteIn; + + + // #pragma Trie Nodes + + + + function ArrayMapNode(ownerID, entries) { + this.ownerID = ownerID; + this.entries = entries; + } + + ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { + var entries = this.entries; + for (var ii = 0, len = entries.length; ii < len; ii++) { + if (is(key, entries[ii][0])) { + return entries[ii][1]; + } + } + return notSetValue; + }; + + ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + var removed = value === NOT_SET; + + var entries = this.entries; + var idx = 0; + for (var len = entries.length; idx < len; idx++) { + if (is(key, entries[idx][0])) { + break; + } + } + var exists = idx < len; + + if (exists ? entries[idx][1] === value : removed) { + return this; + } + + SetRef(didAlter); + (removed || !exists) && SetRef(didChangeSize); + + if (removed && entries.length === 1) { + return; // undefined + } + + if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { + return createNodes(ownerID, entries, key, value); + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newEntries = isEditable ? entries : arrCopy(entries); + + if (exists) { + if (removed) { + idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); + } else { + newEntries[idx] = [key, value]; + } + } else { + newEntries.push([key, value]); + } + + if (isEditable) { + this.entries = newEntries; + return this; + } + + return new ArrayMapNode(ownerID, newEntries); + }; + + + + + function BitmapIndexedNode(ownerID, bitmap, nodes) { + this.ownerID = ownerID; + this.bitmap = bitmap; + this.nodes = nodes; + } + + BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK)); + var bitmap = this.bitmap; + return (bitmap & bit) === 0 ? notSetValue : + this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue); + }; + + BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var bit = 1 << keyHashFrag; + var bitmap = this.bitmap; + var exists = (bitmap & bit) !== 0; + + if (!exists && value === NOT_SET) { + return this; + } + + var idx = popCount(bitmap & (bit - 1)); + var nodes = this.nodes; + var node = exists ? nodes[idx] : undefined; + var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); + + if (newNode === node) { + return this; + } + + if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { + return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); + } + + if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) { + return nodes[idx ^ 1]; + } + + if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { + return newNode; + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit; + var newNodes = exists ? newNode ? + setIn(nodes, idx, newNode, isEditable) : + spliceOut(nodes, idx, isEditable) : + spliceIn(nodes, idx, newNode, isEditable); + + if (isEditable) { + this.bitmap = newBitmap; + this.nodes = newNodes; + return this; + } + + return new BitmapIndexedNode(ownerID, newBitmap, newNodes); + }; + + + + + function HashArrayMapNode(ownerID, count, nodes) { + this.ownerID = ownerID; + this.count = count; + this.nodes = nodes; + } + + HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var node = this.nodes[idx]; + return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue; + }; + + HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var removed = value === NOT_SET; + var nodes = this.nodes; + var node = nodes[idx]; + + if (removed && !node) { + return this; + } + + var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); + if (newNode === node) { + return this; + } + + var newCount = this.count; + if (!node) { + newCount++; + } else if (!newNode) { + newCount--; + if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { + return packNodes(ownerID, nodes, newCount, idx); + } + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newNodes = setIn(nodes, idx, newNode, isEditable); + + if (isEditable) { + this.count = newCount; + this.nodes = newNodes; + return this; + } + + return new HashArrayMapNode(ownerID, newCount, newNodes); + }; + + + + + function HashCollisionNode(ownerID, keyHash, entries) { + this.ownerID = ownerID; + this.keyHash = keyHash; + this.entries = entries; + } + + HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) { + var entries = this.entries; + for (var ii = 0, len = entries.length; ii < len; ii++) { + if (is(key, entries[ii][0])) { + return entries[ii][1]; + } + } + return notSetValue; + }; + + HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } + + var removed = value === NOT_SET; + + if (keyHash !== this.keyHash) { + if (removed) { + return this; + } + SetRef(didAlter); + SetRef(didChangeSize); + return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); + } + + var entries = this.entries; + var idx = 0; + for (var len = entries.length; idx < len; idx++) { + if (is(key, entries[idx][0])) { + break; + } + } + var exists = idx < len; + + if (exists ? entries[idx][1] === value : removed) { + return this; + } + + SetRef(didAlter); + (removed || !exists) && SetRef(didChangeSize); + + if (removed && len === 2) { + return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newEntries = isEditable ? entries : arrCopy(entries); + + if (exists) { + if (removed) { + idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); + } else { + newEntries[idx] = [key, value]; + } + } else { + newEntries.push([key, value]); + } + + if (isEditable) { + this.entries = newEntries; + return this; + } + + return new HashCollisionNode(ownerID, this.keyHash, newEntries); + }; + + + + + function ValueNode(ownerID, keyHash, entry) { + this.ownerID = ownerID; + this.keyHash = keyHash; + this.entry = entry; + } + + ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) { + return is(key, this.entry[0]) ? this.entry[1] : notSetValue; + }; + + ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + var removed = value === NOT_SET; + var keyMatch = is(key, this.entry[0]); + if (keyMatch ? value === this.entry[1] : removed) { + return this; + } + + SetRef(didAlter); + + if (removed) { + SetRef(didChangeSize); + return; // undefined + } + + if (keyMatch) { + if (ownerID && ownerID === this.ownerID) { + this.entry[1] = value; + return this; + } + return new ValueNode(ownerID, this.keyHash, [key, value]); + } + + SetRef(didChangeSize); + return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); + }; + + + + // #pragma Iterators + + ArrayMapNode.prototype.iterate = + HashCollisionNode.prototype.iterate = function (fn, reverse) { + var entries = this.entries; + for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { + if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { + return false; + } + } + } + + BitmapIndexedNode.prototype.iterate = + HashArrayMapNode.prototype.iterate = function (fn, reverse) { + var nodes = this.nodes; + for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { + var node = nodes[reverse ? maxIndex - ii : ii]; + if (node && node.iterate(fn, reverse) === false) { + return false; + } + } + } + + ValueNode.prototype.iterate = function (fn, reverse) { + return fn(this.entry); + } + + createClass(MapIterator, Iterator); + + function MapIterator(map, type, reverse) { + this._type = type; + this._reverse = reverse; + this._stack = map._root && mapIteratorFrame(map._root); + } + + MapIterator.prototype.next = function() { + var type = this._type; + var stack = this._stack; + while (stack) { + var node = stack.node; + var index = stack.index++; + var maxIndex; + if (node.entry) { + if (index === 0) { + return mapIteratorValue(type, node.entry); + } + } else if (node.entries) { + maxIndex = node.entries.length - 1; + if (index <= maxIndex) { + return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]); + } + } else { + maxIndex = node.nodes.length - 1; + if (index <= maxIndex) { + var subNode = node.nodes[this._reverse ? maxIndex - index : index]; + if (subNode) { + if (subNode.entry) { + return mapIteratorValue(type, subNode.entry); + } + stack = this._stack = mapIteratorFrame(subNode, stack); + } + continue; + } + } + stack = this._stack = this._stack.__prev; + } + return iteratorDone(); + }; + + + function mapIteratorValue(type, entry) { + return iteratorValue(type, entry[0], entry[1]); + } + + function mapIteratorFrame(node, prev) { + return { + node: node, + index: 0, + __prev: prev + }; + } + + function makeMap(size, root, ownerID, hash) { + var map = Object.create(MapPrototype); + map.size = size; + map._root = root; + map.__ownerID = ownerID; + map.__hash = hash; + map.__altered = false; + return map; + } + + var EMPTY_MAP; + function emptyMap() { + return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); + } + + function updateMap(map, k, v) { + var newRoot; + var newSize; + if (!map._root) { + if (v === NOT_SET) { + return map; + } + newSize = 1; + newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); + } else { + var didChangeSize = MakeRef(CHANGE_LENGTH); + var didAlter = MakeRef(DID_ALTER); + newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter); + if (!didAlter.value) { + return map; + } + newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0); + } + if (map.__ownerID) { + map.size = newSize; + map._root = newRoot; + map.__hash = undefined; + map.__altered = true; + return map; + } + return newRoot ? makeMap(newSize, newRoot) : emptyMap(); + } + + function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (!node) { + if (value === NOT_SET) { + return node; + } + SetRef(didAlter); + SetRef(didChangeSize); + return new ValueNode(ownerID, keyHash, [key, value]); + } + return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter); + } + + function isLeafNode(node) { + return node.constructor === ValueNode || node.constructor === HashCollisionNode; + } + + function mergeIntoNode(node, ownerID, shift, keyHash, entry) { + if (node.keyHash === keyHash) { + return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); + } + + var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; + var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + + var newNode; + var nodes = idx1 === idx2 ? + [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] : + ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]); + + return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); + } + + function createNodes(ownerID, entries, key, value) { + if (!ownerID) { + ownerID = new OwnerID(); + } + var node = new ValueNode(ownerID, hash(key), [key, value]); + for (var ii = 0; ii < entries.length; ii++) { + var entry = entries[ii]; + node = node.update(ownerID, 0, undefined, entry[0], entry[1]); + } + return node; + } + + function packNodes(ownerID, nodes, count, excluding) { + var bitmap = 0; + var packedII = 0; + var packedNodes = new Array(count); + for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { + var node = nodes[ii]; + if (node !== undefined && ii !== excluding) { + bitmap |= bit; + packedNodes[packedII++] = node; + } + } + return new BitmapIndexedNode(ownerID, bitmap, packedNodes); + } + + function expandNodes(ownerID, nodes, bitmap, including, node) { + var count = 0; + var expandedNodes = new Array(SIZE); + for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { + expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; + } + expandedNodes[including] = node; + return new HashArrayMapNode(ownerID, count + 1, expandedNodes); + } + + function mergeIntoMapWith(map, merger, iterables) { + var iters = []; + for (var ii = 0; ii < iterables.length; ii++) { + var value = iterables[ii]; + var iter = KeyedIterable(value); + if (!isIterable(value)) { + iter = iter.map(function(v ) {return fromJS(v)}); + } + iters.push(iter); + } + return mergeIntoCollectionWith(map, merger, iters); + } + + function deepMerger(existing, value, key) { + return existing && existing.mergeDeep && isIterable(value) ? + existing.mergeDeep(value) : + is(existing, value) ? existing : value; + } + + function deepMergerWith(merger) { + return function(existing, value, key) { + if (existing && existing.mergeDeepWith && isIterable(value)) { + return existing.mergeDeepWith(merger, value); + } + var nextValue = merger(existing, value, key); + return is(existing, nextValue) ? existing : nextValue; + }; + } + + function mergeIntoCollectionWith(collection, merger, iters) { + iters = iters.filter(function(x ) {return x.size !== 0}); + if (iters.length === 0) { + return collection; + } + if (collection.size === 0 && !collection.__ownerID && iters.length === 1) { + return collection.constructor(iters[0]); + } + return collection.withMutations(function(collection ) { + var mergeIntoMap = merger ? + function(value, key) { + collection.update(key, NOT_SET, function(existing ) + {return existing === NOT_SET ? value : merger(existing, value, key)} + ); + } : + function(value, key) { + collection.set(key, value); + } + for (var ii = 0; ii < iters.length; ii++) { + iters[ii].forEach(mergeIntoMap); + } + }); + } + + function updateInDeepMap(existing, keyPathIter, notSetValue, updater) { + var isNotSet = existing === NOT_SET; + var step = keyPathIter.next(); + if (step.done) { + var existingValue = isNotSet ? notSetValue : existing; + var newValue = updater(existingValue); + return newValue === existingValue ? existing : newValue; + } + invariant( + isNotSet || (existing && existing.set), + 'invalid keyPath' + ); + var key = step.value; + var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET); + var nextUpdated = updateInDeepMap( + nextExisting, + keyPathIter, + notSetValue, + updater + ); + return nextUpdated === nextExisting ? existing : + nextUpdated === NOT_SET ? existing.remove(key) : + (isNotSet ? emptyMap() : existing).set(key, nextUpdated); + } + + function popCount(x) { + x = x - ((x >> 1) & 0x55555555); + x = (x & 0x33333333) + ((x >> 2) & 0x33333333); + x = (x + (x >> 4)) & 0x0f0f0f0f; + x = x + (x >> 8); + x = x + (x >> 16); + return x & 0x7f; + } + + function setIn(array, idx, val, canEdit) { + var newArray = canEdit ? array : arrCopy(array); + newArray[idx] = val; + return newArray; + } + + function spliceIn(array, idx, val, canEdit) { + var newLen = array.length + 1; + if (canEdit && idx + 1 === newLen) { + array[idx] = val; + return array; + } + var newArray = new Array(newLen); + var after = 0; + for (var ii = 0; ii < newLen; ii++) { + if (ii === idx) { + newArray[ii] = val; + after = -1; + } else { + newArray[ii] = array[ii + after]; + } + } + return newArray; + } + + function spliceOut(array, idx, canEdit) { + var newLen = array.length - 1; + if (canEdit && idx === newLen) { + array.pop(); + return array; + } + var newArray = new Array(newLen); + var after = 0; + for (var ii = 0; ii < newLen; ii++) { + if (ii === idx) { + after = 1; + } + newArray[ii] = array[ii + after]; + } + return newArray; + } + + var MAX_ARRAY_MAP_SIZE = SIZE / 4; + var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; + var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; + + createClass(List, IndexedCollection); + + // @pragma Construction + + function List(value) { + var empty = emptyList(); + if (value === null || value === undefined) { + return empty; + } + if (isList(value)) { + return value; + } + var iter = IndexedIterable(value); + var size = iter.size; + if (size === 0) { + return empty; + } + assertNotInfinite(size); + if (size > 0 && size < SIZE) { + return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); + } + return empty.withMutations(function(list ) { + list.setSize(size); + iter.forEach(function(v, i) {return list.set(i, v)}); + }); + } + + List.of = function(/*...values*/) { + return this(arguments); + }; + + List.prototype.toString = function() { + return this.__toString('List [', ']'); + }; + + // @pragma Access + + List.prototype.get = function(index, notSetValue) { + index = wrapIndex(this, index); + if (index >= 0 && index < this.size) { + index += this._origin; + var node = listNodeFor(this, index); + return node && node.array[index & MASK]; + } + return notSetValue; + }; + + // @pragma Modification + + List.prototype.set = function(index, value) { + return updateList(this, index, value); + }; + + List.prototype.remove = function(index) { + return !this.has(index) ? this : + index === 0 ? this.shift() : + index === this.size - 1 ? this.pop() : + this.splice(index, 1); + }; + + List.prototype.insert = function(index, value) { + return this.splice(index, 0, value); + }; + + List.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = this._origin = this._capacity = 0; + this._level = SHIFT; + this._root = this._tail = null; + this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyList(); + }; + + List.prototype.push = function(/*...values*/) { + var values = arguments; + var oldSize = this.size; + return this.withMutations(function(list ) { + setListBounds(list, 0, oldSize + values.length); + for (var ii = 0; ii < values.length; ii++) { + list.set(oldSize + ii, values[ii]); + } + }); + }; + + List.prototype.pop = function() { + return setListBounds(this, 0, -1); + }; + + List.prototype.unshift = function(/*...values*/) { + var values = arguments; + return this.withMutations(function(list ) { + setListBounds(list, -values.length); + for (var ii = 0; ii < values.length; ii++) { + list.set(ii, values[ii]); + } + }); + }; + + List.prototype.shift = function() { + return setListBounds(this, 1); + }; + + // @pragma Composition + + List.prototype.merge = function(/*...iters*/) { + return mergeIntoListWith(this, undefined, arguments); + }; + + List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoListWith(this, merger, iters); + }; + + List.prototype.mergeDeep = function(/*...iters*/) { + return mergeIntoListWith(this, deepMerger, arguments); + }; + + List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoListWith(this, deepMergerWith(merger), iters); + }; + + List.prototype.setSize = function(size) { + return setListBounds(this, 0, size); + }; + + // @pragma Iteration + + List.prototype.slice = function(begin, end) { + var size = this.size; + if (wholeSlice(begin, end, size)) { + return this; + } + return setListBounds( + this, + resolveBegin(begin, size), + resolveEnd(end, size) + ); + }; + + List.prototype.__iterator = function(type, reverse) { + var index = 0; + var values = iterateList(this, reverse); + return new Iterator(function() { + var value = values(); + return value === DONE ? + iteratorDone() : + iteratorValue(type, index++, value); + }); + }; + + List.prototype.__iterate = function(fn, reverse) { + var index = 0; + var values = iterateList(this, reverse); + var value; + while ((value = values()) !== DONE) { + if (fn(value, index++, this) === false) { + break; + } + } + return index; + }; + + List.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + this.__ownerID = ownerID; + return this; + } + return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash); + }; + + + function isList(maybeList) { + return !!(maybeList && maybeList[IS_LIST_SENTINEL]); + } + + List.isList = isList; + + var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; + + var ListPrototype = List.prototype; + ListPrototype[IS_LIST_SENTINEL] = true; + ListPrototype[DELETE] = ListPrototype.remove; + ListPrototype.setIn = MapPrototype.setIn; + ListPrototype.deleteIn = + ListPrototype.removeIn = MapPrototype.removeIn; + ListPrototype.update = MapPrototype.update; + ListPrototype.updateIn = MapPrototype.updateIn; + ListPrototype.mergeIn = MapPrototype.mergeIn; + ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; + ListPrototype.withMutations = MapPrototype.withMutations; + ListPrototype.asMutable = MapPrototype.asMutable; + ListPrototype.asImmutable = MapPrototype.asImmutable; + ListPrototype.wasAltered = MapPrototype.wasAltered; + + + + function VNode(array, ownerID) { + this.array = array; + this.ownerID = ownerID; + } + + // TODO: seems like these methods are very similar + + VNode.prototype.removeBefore = function(ownerID, level, index) { + if (index === level ? 1 << level : 0 || this.array.length === 0) { + return this; + } + var originIndex = (index >>> level) & MASK; + if (originIndex >= this.array.length) { + return new VNode([], ownerID); + } + var removingFirst = originIndex === 0; + var newChild; + if (level > 0) { + var oldChild = this.array[originIndex]; + newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); + if (newChild === oldChild && removingFirst) { + return this; + } + } + if (removingFirst && !newChild) { + return this; + } + var editable = editableVNode(this, ownerID); + if (!removingFirst) { + for (var ii = 0; ii < originIndex; ii++) { + editable.array[ii] = undefined; + } + } + if (newChild) { + editable.array[originIndex] = newChild; + } + return editable; + }; + + VNode.prototype.removeAfter = function(ownerID, level, index) { + if (index === (level ? 1 << level : 0) || this.array.length === 0) { + return this; + } + var sizeIndex = ((index - 1) >>> level) & MASK; + if (sizeIndex >= this.array.length) { + return this; + } + + var newChild; + if (level > 0) { + var oldChild = this.array[sizeIndex]; + newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); + if (newChild === oldChild && sizeIndex === this.array.length - 1) { + return this; + } + } + + var editable = editableVNode(this, ownerID); + editable.array.splice(sizeIndex + 1); + if (newChild) { + editable.array[sizeIndex] = newChild; + } + return editable; + }; + + + + var DONE = {}; + + function iterateList(list, reverse) { + var left = list._origin; + var right = list._capacity; + var tailPos = getTailOffset(right); + var tail = list._tail; + + return iterateNodeOrLeaf(list._root, list._level, 0); + + function iterateNodeOrLeaf(node, level, offset) { + return level === 0 ? + iterateLeaf(node, offset) : + iterateNode(node, level, offset); + } + + function iterateLeaf(node, offset) { + var array = offset === tailPos ? tail && tail.array : node && node.array; + var from = offset > left ? 0 : left - offset; + var to = right - offset; + if (to > SIZE) { + to = SIZE; + } + return function() { + if (from === to) { + return DONE; + } + var idx = reverse ? --to : from++; + return array && array[idx]; + }; + } + + function iterateNode(node, level, offset) { + var values; + var array = node && node.array; + var from = offset > left ? 0 : (left - offset) >> level; + var to = ((right - offset) >> level) + 1; + if (to > SIZE) { + to = SIZE; + } + return function() { + do { + if (values) { + var value = values(); + if (value !== DONE) { + return value; + } + values = null; + } + if (from === to) { + return DONE; + } + var idx = reverse ? --to : from++; + values = iterateNodeOrLeaf( + array && array[idx], level - SHIFT, offset + (idx << level) + ); + } while (true); + }; + } + } + + function makeList(origin, capacity, level, root, tail, ownerID, hash) { + var list = Object.create(ListPrototype); + list.size = capacity - origin; + list._origin = origin; + list._capacity = capacity; + list._level = level; + list._root = root; + list._tail = tail; + list.__ownerID = ownerID; + list.__hash = hash; + list.__altered = false; + return list; + } + + var EMPTY_LIST; + function emptyList() { + return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT)); + } + + function updateList(list, index, value) { + index = wrapIndex(list, index); + + if (index !== index) { + return list; + } + + if (index >= list.size || index < 0) { + return list.withMutations(function(list ) { + index < 0 ? + setListBounds(list, index).set(0, value) : + setListBounds(list, 0, index + 1).set(index, value) + }); + } + + index += list._origin; + + var newTail = list._tail; + var newRoot = list._root; + var didAlter = MakeRef(DID_ALTER); + if (index >= getTailOffset(list._capacity)) { + newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); + } else { + newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter); + } + + if (!didAlter.value) { + return list; + } + + if (list.__ownerID) { + list._root = newRoot; + list._tail = newTail; + list.__hash = undefined; + list.__altered = true; + return list; + } + return makeList(list._origin, list._capacity, list._level, newRoot, newTail); + } + + function updateVNode(node, ownerID, level, index, value, didAlter) { + var idx = (index >>> level) & MASK; + var nodeHas = node && idx < node.array.length; + if (!nodeHas && value === undefined) { + return node; + } + + var newNode; + + if (level > 0) { + var lowerNode = node && node.array[idx]; + var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter); + if (newLowerNode === lowerNode) { + return node; + } + newNode = editableVNode(node, ownerID); + newNode.array[idx] = newLowerNode; + return newNode; + } + + if (nodeHas && node.array[idx] === value) { + return node; + } + + SetRef(didAlter); + + newNode = editableVNode(node, ownerID); + if (value === undefined && idx === newNode.array.length - 1) { + newNode.array.pop(); + } else { + newNode.array[idx] = value; + } + return newNode; + } + + function editableVNode(node, ownerID) { + if (ownerID && node && ownerID === node.ownerID) { + return node; + } + return new VNode(node ? node.array.slice() : [], ownerID); + } + + function listNodeFor(list, rawIndex) { + if (rawIndex >= getTailOffset(list._capacity)) { + return list._tail; + } + if (rawIndex < 1 << (list._level + SHIFT)) { + var node = list._root; + var level = list._level; + while (node && level > 0) { + node = node.array[(rawIndex >>> level) & MASK]; + level -= SHIFT; + } + return node; + } + } + + function setListBounds(list, begin, end) { + // Sanitize begin & end using this shorthand for ToInt32(argument) + // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 + if (begin !== undefined) { + begin = begin | 0; + } + if (end !== undefined) { + end = end | 0; + } + var owner = list.__ownerID || new OwnerID(); + var oldOrigin = list._origin; + var oldCapacity = list._capacity; + var newOrigin = oldOrigin + begin; + var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end; + if (newOrigin === oldOrigin && newCapacity === oldCapacity) { + return list; + } + + // If it's going to end after it starts, it's empty. + if (newOrigin >= newCapacity) { + return list.clear(); + } + + var newLevel = list._level; + var newRoot = list._root; + + // New origin might need creating a higher root. + var offsetShift = 0; + while (newOrigin + offsetShift < 0) { + newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner); + newLevel += SHIFT; + offsetShift += 1 << newLevel; + } + if (offsetShift) { + newOrigin += offsetShift; + oldOrigin += offsetShift; + newCapacity += offsetShift; + oldCapacity += offsetShift; + } + + var oldTailOffset = getTailOffset(oldCapacity); + var newTailOffset = getTailOffset(newCapacity); + + // New size might need creating a higher root. + while (newTailOffset >= 1 << (newLevel + SHIFT)) { + newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner); + newLevel += SHIFT; + } + + // Locate or create the new tail. + var oldTail = list._tail; + var newTail = newTailOffset < oldTailOffset ? + listNodeFor(list, newCapacity - 1) : + newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail; + + // Merge Tail into tree. + if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) { + newRoot = editableVNode(newRoot, owner); + var node = newRoot; + for (var level = newLevel; level > SHIFT; level -= SHIFT) { + var idx = (oldTailOffset >>> level) & MASK; + node = node.array[idx] = editableVNode(node.array[idx], owner); + } + node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; + } + + // If the size has been reduced, there's a chance the tail needs to be trimmed. + if (newCapacity < oldCapacity) { + newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); + } + + // If the new origin is within the tail, then we do not need a root. + if (newOrigin >= newTailOffset) { + newOrigin -= newTailOffset; + newCapacity -= newTailOffset; + newLevel = SHIFT; + newRoot = null; + newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); + + // Otherwise, if the root has been trimmed, garbage collect. + } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { + offsetShift = 0; + + // Identify the new top root node of the subtree of the old root. + while (newRoot) { + var beginIndex = (newOrigin >>> newLevel) & MASK; + if (beginIndex !== (newTailOffset >>> newLevel) & MASK) { + break; + } + if (beginIndex) { + offsetShift += (1 << newLevel) * beginIndex; + } + newLevel -= SHIFT; + newRoot = newRoot.array[beginIndex]; + } + + // Trim the new sides of the new root. + if (newRoot && newOrigin > oldOrigin) { + newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); + } + if (newRoot && newTailOffset < oldTailOffset) { + newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift); + } + if (offsetShift) { + newOrigin -= offsetShift; + newCapacity -= offsetShift; + } + } + + if (list.__ownerID) { + list.size = newCapacity - newOrigin; + list._origin = newOrigin; + list._capacity = newCapacity; + list._level = newLevel; + list._root = newRoot; + list._tail = newTail; + list.__hash = undefined; + list.__altered = true; + return list; + } + return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); + } + + function mergeIntoListWith(list, merger, iterables) { + var iters = []; + var maxSize = 0; + for (var ii = 0; ii < iterables.length; ii++) { + var value = iterables[ii]; + var iter = IndexedIterable(value); + if (iter.size > maxSize) { + maxSize = iter.size; + } + if (!isIterable(value)) { + iter = iter.map(function(v ) {return fromJS(v)}); + } + iters.push(iter); + } + if (maxSize > list.size) { + list = list.setSize(maxSize); + } + return mergeIntoCollectionWith(list, merger, iters); + } + + function getTailOffset(size) { + return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT); + } + + createClass(OrderedMap, Map); + + // @pragma Construction + + function OrderedMap(value) { + return value === null || value === undefined ? emptyOrderedMap() : + isOrderedMap(value) ? value : + emptyOrderedMap().withMutations(function(map ) { + var iter = KeyedIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v, k) {return map.set(k, v)}); + }); + } + + OrderedMap.of = function(/*...values*/) { + return this(arguments); + }; + + OrderedMap.prototype.toString = function() { + return this.__toString('OrderedMap {', '}'); + }; + + // @pragma Access + + OrderedMap.prototype.get = function(k, notSetValue) { + var index = this._map.get(k); + return index !== undefined ? this._list.get(index)[1] : notSetValue; + }; + + // @pragma Modification + + OrderedMap.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._map.clear(); + this._list.clear(); + return this; + } + return emptyOrderedMap(); + }; + + OrderedMap.prototype.set = function(k, v) { + return updateOrderedMap(this, k, v); + }; + + OrderedMap.prototype.remove = function(k) { + return updateOrderedMap(this, k, NOT_SET); + }; + + OrderedMap.prototype.wasAltered = function() { + return this._map.wasAltered() || this._list.wasAltered(); + }; + + OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._list.__iterate( + function(entry ) {return entry && fn(entry[1], entry[0], this$0)}, + reverse + ); + }; + + OrderedMap.prototype.__iterator = function(type, reverse) { + return this._list.fromEntrySeq().__iterator(type, reverse); + }; + + OrderedMap.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + var newMap = this._map.__ensureOwner(ownerID); + var newList = this._list.__ensureOwner(ownerID); + if (!ownerID) { + this.__ownerID = ownerID; + this._map = newMap; + this._list = newList; + return this; + } + return makeOrderedMap(newMap, newList, ownerID, this.__hash); + }; + + + function isOrderedMap(maybeOrderedMap) { + return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); + } + + OrderedMap.isOrderedMap = isOrderedMap; + + OrderedMap.prototype[IS_ORDERED_SENTINEL] = true; + OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; + + + + function makeOrderedMap(map, list, ownerID, hash) { + var omap = Object.create(OrderedMap.prototype); + omap.size = map ? map.size : 0; + omap._map = map; + omap._list = list; + omap.__ownerID = ownerID; + omap.__hash = hash; + return omap; + } + + var EMPTY_ORDERED_MAP; + function emptyOrderedMap() { + return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())); + } + + function updateOrderedMap(omap, k, v) { + var map = omap._map; + var list = omap._list; + var i = map.get(k); + var has = i !== undefined; + var newMap; + var newList; + if (v === NOT_SET) { // removed + if (!has) { + return omap; + } + if (list.size >= SIZE && list.size >= map.size * 2) { + newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx}); + newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap(); + if (omap.__ownerID) { + newMap.__ownerID = newList.__ownerID = omap.__ownerID; + } + } else { + newMap = map.remove(k); + newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); + } + } else { + if (has) { + if (v === list.get(i)[1]) { + return omap; + } + newMap = map; + newList = list.set(i, [k, v]); + } else { + newMap = map.set(k, list.size); + newList = list.set(list.size, [k, v]); + } + } + if (omap.__ownerID) { + omap.size = newMap.size; + omap._map = newMap; + omap._list = newList; + omap.__hash = undefined; + return omap; + } + return makeOrderedMap(newMap, newList); + } + + createClass(ToKeyedSequence, KeyedSeq); + function ToKeyedSequence(indexed, useKeys) { + this._iter = indexed; + this._useKeys = useKeys; + this.size = indexed.size; + } + + ToKeyedSequence.prototype.get = function(key, notSetValue) { + return this._iter.get(key, notSetValue); + }; + + ToKeyedSequence.prototype.has = function(key) { + return this._iter.has(key); + }; + + ToKeyedSequence.prototype.valueSeq = function() { + return this._iter.valueSeq(); + }; + + ToKeyedSequence.prototype.reverse = function() {var this$0 = this; + var reversedSequence = reverseFactory(this, true); + if (!this._useKeys) { + reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()}; + } + return reversedSequence; + }; + + ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this; + var mappedSequence = mapFactory(this, mapper, context); + if (!this._useKeys) { + mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)}; + } + return mappedSequence; + }; + + ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + var ii; + return this._iter.__iterate( + this._useKeys ? + function(v, k) {return fn(v, k, this$0)} : + ((ii = reverse ? resolveSize(this) : 0), + function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}), + reverse + ); + }; + + ToKeyedSequence.prototype.__iterator = function(type, reverse) { + if (this._useKeys) { + return this._iter.__iterator(type, reverse); + } + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + var ii = reverse ? resolveSize(this) : 0; + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : + iteratorValue(type, reverse ? --ii : ii++, step.value, step); + }); + }; + + ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true; + + + createClass(ToIndexedSequence, IndexedSeq); + function ToIndexedSequence(iter) { + this._iter = iter; + this.size = iter.size; + } + + ToIndexedSequence.prototype.includes = function(value) { + return this._iter.includes(value); + }; + + ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + var iterations = 0; + return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse); + }; + + ToIndexedSequence.prototype.__iterator = function(type, reverse) { + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + var iterations = 0; + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : + iteratorValue(type, iterations++, step.value, step) + }); + }; + + + + createClass(ToSetSequence, SetSeq); + function ToSetSequence(iter) { + this._iter = iter; + this.size = iter.size; + } + + ToSetSequence.prototype.has = function(key) { + return this._iter.includes(key); + }; + + ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse); + }; + + ToSetSequence.prototype.__iterator = function(type, reverse) { + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : + iteratorValue(type, step.value, step.value, step); + }); + }; + + + + createClass(FromEntriesSequence, KeyedSeq); + function FromEntriesSequence(entries) { + this._iter = entries; + this.size = entries.size; + } + + FromEntriesSequence.prototype.entrySeq = function() { + return this._iter.toSeq(); + }; + + FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._iter.__iterate(function(entry ) { + // Check if entry exists first so array access doesn't throw for holes + // in the parent iteration. + if (entry) { + validateEntry(entry); + var indexedIterable = isIterable(entry); + return fn( + indexedIterable ? entry.get(1) : entry[1], + indexedIterable ? entry.get(0) : entry[0], + this$0 + ); + } + }, reverse); + }; + + FromEntriesSequence.prototype.__iterator = function(type, reverse) { + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + return new Iterator(function() { + while (true) { + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + // Check if entry exists first so array access doesn't throw for holes + // in the parent iteration. + if (entry) { + validateEntry(entry); + var indexedIterable = isIterable(entry); + return iteratorValue( + type, + indexedIterable ? entry.get(0) : entry[0], + indexedIterable ? entry.get(1) : entry[1], + step + ); + } + } + }); + }; + + + ToIndexedSequence.prototype.cacheResult = + ToKeyedSequence.prototype.cacheResult = + ToSetSequence.prototype.cacheResult = + FromEntriesSequence.prototype.cacheResult = + cacheResultThrough; + + + function flipFactory(iterable) { + var flipSequence = makeSequence(iterable); + flipSequence._iter = iterable; + flipSequence.size = iterable.size; + flipSequence.flip = function() {return iterable}; + flipSequence.reverse = function () { + var reversedSequence = iterable.reverse.apply(this); // super.reverse() + reversedSequence.flip = function() {return iterable.reverse()}; + return reversedSequence; + }; + flipSequence.has = function(key ) {return iterable.includes(key)}; + flipSequence.includes = function(key ) {return iterable.has(key)}; + flipSequence.cacheResult = cacheResultThrough; + flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse); + } + flipSequence.__iteratorUncached = function(type, reverse) { + if (type === ITERATE_ENTRIES) { + var iterator = iterable.__iterator(type, reverse); + return new Iterator(function() { + var step = iterator.next(); + if (!step.done) { + var k = step.value[0]; + step.value[0] = step.value[1]; + step.value[1] = k; + } + return step; + }); + } + return iterable.__iterator( + type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, + reverse + ); + } + return flipSequence; + } + + + function mapFactory(iterable, mapper, context) { + var mappedSequence = makeSequence(iterable); + mappedSequence.size = iterable.size; + mappedSequence.has = function(key ) {return iterable.has(key)}; + mappedSequence.get = function(key, notSetValue) { + var v = iterable.get(key, NOT_SET); + return v === NOT_SET ? + notSetValue : + mapper.call(context, v, key, iterable); + }; + mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + return iterable.__iterate( + function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false}, + reverse + ); + } + mappedSequence.__iteratorUncached = function (type, reverse) { + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + return new Iterator(function() { + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + var key = entry[0]; + return iteratorValue( + type, + key, + mapper.call(context, entry[1], key, iterable), + step + ); + }); + } + return mappedSequence; + } + + + function reverseFactory(iterable, useKeys) { + var reversedSequence = makeSequence(iterable); + reversedSequence._iter = iterable; + reversedSequence.size = iterable.size; + reversedSequence.reverse = function() {return iterable}; + if (iterable.flip) { + reversedSequence.flip = function () { + var flipSequence = flipFactory(iterable); + flipSequence.reverse = function() {return iterable.flip()}; + return flipSequence; + }; + } + reversedSequence.get = function(key, notSetValue) + {return iterable.get(useKeys ? key : -1 - key, notSetValue)}; + reversedSequence.has = function(key ) + {return iterable.has(useKeys ? key : -1 - key)}; + reversedSequence.includes = function(value ) {return iterable.includes(value)}; + reversedSequence.cacheResult = cacheResultThrough; + reversedSequence.__iterate = function (fn, reverse) {var this$0 = this; + return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse); + }; + reversedSequence.__iterator = + function(type, reverse) {return iterable.__iterator(type, !reverse)}; + return reversedSequence; + } + + + function filterFactory(iterable, predicate, context, useKeys) { + var filterSequence = makeSequence(iterable); + if (useKeys) { + filterSequence.has = function(key ) { + var v = iterable.get(key, NOT_SET); + return v !== NOT_SET && !!predicate.call(context, v, key, iterable); + }; + filterSequence.get = function(key, notSetValue) { + var v = iterable.get(key, NOT_SET); + return v !== NOT_SET && predicate.call(context, v, key, iterable) ? + v : notSetValue; + }; + } + filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + var iterations = 0; + iterable.__iterate(function(v, k, c) { + if (predicate.call(context, v, k, c)) { + iterations++; + return fn(v, useKeys ? k : iterations - 1, this$0); + } + }, reverse); + return iterations; + }; + filterSequence.__iteratorUncached = function (type, reverse) { + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + var iterations = 0; + return new Iterator(function() { + while (true) { + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + var key = entry[0]; + var value = entry[1]; + if (predicate.call(context, value, key, iterable)) { + return iteratorValue(type, useKeys ? key : iterations++, value, step); + } + } + }); + } + return filterSequence; + } + + + function countByFactory(iterable, grouper, context) { + var groups = Map().asMutable(); + iterable.__iterate(function(v, k) { + groups.update( + grouper.call(context, v, k, iterable), + 0, + function(a ) {return a + 1} + ); + }); + return groups.asImmutable(); + } + + + function groupByFactory(iterable, grouper, context) { + var isKeyedIter = isKeyed(iterable); + var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable(); + iterable.__iterate(function(v, k) { + groups.update( + grouper.call(context, v, k, iterable), + function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)} + ); + }); + var coerce = iterableClass(iterable); + return groups.map(function(arr ) {return reify(iterable, coerce(arr))}); + } + + + function sliceFactory(iterable, begin, end, useKeys) { + var originalSize = iterable.size; + + // Sanitize begin & end using this shorthand for ToInt32(argument) + // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 + if (begin !== undefined) { + begin = begin | 0; + } + if (end !== undefined) { + end = end | 0; + } + + if (wholeSlice(begin, end, originalSize)) { + return iterable; + } + + var resolvedBegin = resolveBegin(begin, originalSize); + var resolvedEnd = resolveEnd(end, originalSize); + + // begin or end will be NaN if they were provided as negative numbers and + // this iterable's size is unknown. In that case, cache first so there is + // a known size and these do not resolve to NaN. + if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) { + return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys); + } + + // Note: resolvedEnd is undefined when the original sequence's length is + // unknown and this slice did not supply an end and should contain all + // elements after resolvedBegin. + // In that case, resolvedSize will be NaN and sliceSize will remain undefined. + var resolvedSize = resolvedEnd - resolvedBegin; + var sliceSize; + if (resolvedSize === resolvedSize) { + sliceSize = resolvedSize < 0 ? 0 : resolvedSize; + } + + var sliceSeq = makeSequence(iterable); + + // If iterable.size is undefined, the size of the realized sliceSeq is + // unknown at this point unless the number of items to slice is 0 + sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined; + + if (!useKeys && isSeq(iterable) && sliceSize >= 0) { + sliceSeq.get = function (index, notSetValue) { + index = wrapIndex(this, index); + return index >= 0 && index < sliceSize ? + iterable.get(index + resolvedBegin, notSetValue) : + notSetValue; + } + } + + sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this; + if (sliceSize === 0) { + return 0; + } + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var skipped = 0; + var isSkipping = true; + var iterations = 0; + iterable.__iterate(function(v, k) { + if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { + iterations++; + return fn(v, useKeys ? k : iterations - 1, this$0) !== false && + iterations !== sliceSize; + } + }); + return iterations; + }; + + sliceSeq.__iteratorUncached = function(type, reverse) { + if (sliceSize !== 0 && reverse) { + return this.cacheResult().__iterator(type, reverse); + } + // Don't bother instantiating parent iterator if taking 0. + var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse); + var skipped = 0; + var iterations = 0; + return new Iterator(function() { + while (skipped++ < resolvedBegin) { + iterator.next(); + } + if (++iterations > sliceSize) { + return iteratorDone(); + } + var step = iterator.next(); + if (useKeys || type === ITERATE_VALUES) { + return step; + } else if (type === ITERATE_KEYS) { + return iteratorValue(type, iterations - 1, undefined, step); + } else { + return iteratorValue(type, iterations - 1, step.value[1], step); + } + }); + } + + return sliceSeq; + } + + + function takeWhileFactory(iterable, predicate, context) { + var takeSequence = makeSequence(iterable); + takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var iterations = 0; + iterable.__iterate(function(v, k, c) + {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)} + ); + return iterations; + }; + takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + var iterating = true; + return new Iterator(function() { + if (!iterating) { + return iteratorDone(); + } + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + var k = entry[0]; + var v = entry[1]; + if (!predicate.call(context, v, k, this$0)) { + iterating = false; + return iteratorDone(); + } + return type === ITERATE_ENTRIES ? step : + iteratorValue(type, k, v, step); + }); + }; + return takeSequence; + } + + + function skipWhileFactory(iterable, predicate, context, useKeys) { + var skipSequence = makeSequence(iterable); + skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var isSkipping = true; + var iterations = 0; + iterable.__iterate(function(v, k, c) { + if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { + iterations++; + return fn(v, useKeys ? k : iterations - 1, this$0); + } + }); + return iterations; + }; + skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + var skipping = true; + var iterations = 0; + return new Iterator(function() { + var step, k, v; + do { + step = iterator.next(); + if (step.done) { + if (useKeys || type === ITERATE_VALUES) { + return step; + } else if (type === ITERATE_KEYS) { + return iteratorValue(type, iterations++, undefined, step); + } else { + return iteratorValue(type, iterations++, step.value[1], step); + } + } + var entry = step.value; + k = entry[0]; + v = entry[1]; + skipping && (skipping = predicate.call(context, v, k, this$0)); + } while (skipping); + return type === ITERATE_ENTRIES ? step : + iteratorValue(type, k, v, step); + }); + }; + return skipSequence; + } + + + function concatFactory(iterable, values) { + var isKeyedIterable = isKeyed(iterable); + var iters = [iterable].concat(values).map(function(v ) { + if (!isIterable(v)) { + v = isKeyedIterable ? + keyedSeqFromValue(v) : + indexedSeqFromValue(Array.isArray(v) ? v : [v]); + } else if (isKeyedIterable) { + v = KeyedIterable(v); + } + return v; + }).filter(function(v ) {return v.size !== 0}); + + if (iters.length === 0) { + return iterable; + } + + if (iters.length === 1) { + var singleton = iters[0]; + if (singleton === iterable || + isKeyedIterable && isKeyed(singleton) || + isIndexed(iterable) && isIndexed(singleton)) { + return singleton; + } + } + + var concatSeq = new ArraySeq(iters); + if (isKeyedIterable) { + concatSeq = concatSeq.toKeyedSeq(); + } else if (!isIndexed(iterable)) { + concatSeq = concatSeq.toSetSeq(); + } + concatSeq = concatSeq.flatten(true); + concatSeq.size = iters.reduce( + function(sum, seq) { + if (sum !== undefined) { + var size = seq.size; + if (size !== undefined) { + return sum + size; + } + } + }, + 0 + ); + return concatSeq; + } + + + function flattenFactory(iterable, depth, useKeys) { + var flatSequence = makeSequence(iterable); + flatSequence.__iterateUncached = function(fn, reverse) { + var iterations = 0; + var stopped = false; + function flatDeep(iter, currentDepth) {var this$0 = this; + iter.__iterate(function(v, k) { + if ((!depth || currentDepth < depth) && isIterable(v)) { + flatDeep(v, currentDepth + 1); + } else if (fn(v, useKeys ? k : iterations++, this$0) === false) { + stopped = true; + } + return !stopped; + }, reverse); + } + flatDeep(iterable, 0); + return iterations; + } + flatSequence.__iteratorUncached = function(type, reverse) { + var iterator = iterable.__iterator(type, reverse); + var stack = []; + var iterations = 0; + return new Iterator(function() { + while (iterator) { + var step = iterator.next(); + if (step.done !== false) { + iterator = stack.pop(); + continue; + } + var v = step.value; + if (type === ITERATE_ENTRIES) { + v = v[1]; + } + if ((!depth || stack.length < depth) && isIterable(v)) { + stack.push(iterator); + iterator = v.__iterator(type, reverse); + } else { + return useKeys ? step : iteratorValue(type, iterations++, v, step); + } + } + return iteratorDone(); + }); + } + return flatSequence; + } + + + function flatMapFactory(iterable, mapper, context) { + var coerce = iterableClass(iterable); + return iterable.toSeq().map( + function(v, k) {return coerce(mapper.call(context, v, k, iterable))} + ).flatten(true); + } + + + function interposeFactory(iterable, separator) { + var interposedSequence = makeSequence(iterable); + interposedSequence.size = iterable.size && iterable.size * 2 -1; + interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; + var iterations = 0; + iterable.__iterate(function(v, k) + {return (!iterations || fn(separator, iterations++, this$0) !== false) && + fn(v, iterations++, this$0) !== false}, + reverse + ); + return iterations; + }; + interposedSequence.__iteratorUncached = function(type, reverse) { + var iterator = iterable.__iterator(ITERATE_VALUES, reverse); + var iterations = 0; + var step; + return new Iterator(function() { + if (!step || iterations % 2) { + step = iterator.next(); + if (step.done) { + return step; + } + } + return iterations % 2 ? + iteratorValue(type, iterations++, separator) : + iteratorValue(type, iterations++, step.value, step); + }); + }; + return interposedSequence; + } + + + function sortFactory(iterable, comparator, mapper) { + if (!comparator) { + comparator = defaultComparator; + } + var isKeyedIterable = isKeyed(iterable); + var index = 0; + var entries = iterable.toSeq().map( + function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]} + ).toArray(); + entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach( + isKeyedIterable ? + function(v, i) { entries[i].length = 2; } : + function(v, i) { entries[i] = v[1]; } + ); + return isKeyedIterable ? KeyedSeq(entries) : + isIndexed(iterable) ? IndexedSeq(entries) : + SetSeq(entries); + } + + + function maxFactory(iterable, comparator, mapper) { + if (!comparator) { + comparator = defaultComparator; + } + if (mapper) { + var entry = iterable.toSeq() + .map(function(v, k) {return [v, mapper(v, k, iterable)]}) + .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a}); + return entry && entry[0]; + } else { + return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a}); + } + } + + function maxCompare(comparator, a, b) { + var comp = comparator(b, a); + // b is considered the new max if the comparator declares them equal, but + // they are not equal and b is in fact a nullish value. + return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0; + } + + + function zipWithFactory(keyIter, zipper, iters) { + var zipSequence = makeSequence(keyIter); + zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min(); + // Note: this a generic base implementation of __iterate in terms of + // __iterator which may be more generically useful in the future. + zipSequence.__iterate = function(fn, reverse) { + /* generic: + var iterator = this.__iterator(ITERATE_ENTRIES, reverse); + var step; + var iterations = 0; + while (!(step = iterator.next()).done) { + iterations++; + if (fn(step.value[1], step.value[0], this) === false) { + break; + } + } + return iterations; + */ + // indexed: + var iterator = this.__iterator(ITERATE_VALUES, reverse); + var step; + var iterations = 0; + while (!(step = iterator.next()).done) { + if (fn(step.value, iterations++, this) === false) { + break; + } + } + return iterations; + }; + zipSequence.__iteratorUncached = function(type, reverse) { + var iterators = iters.map(function(i ) + {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))} + ); + var iterations = 0; + var isDone = false; + return new Iterator(function() { + var steps; + if (!isDone) { + steps = iterators.map(function(i ) {return i.next()}); + isDone = steps.some(function(s ) {return s.done}); + } + if (isDone) { + return iteratorDone(); + } + return iteratorValue( + type, + iterations++, + zipper.apply(null, steps.map(function(s ) {return s.value})) + ); + }); + }; + return zipSequence + } + + + // #pragma Helper Functions + + function reify(iter, seq) { + return isSeq(iter) ? seq : iter.constructor(seq); + } + + function validateEntry(entry) { + if (entry !== Object(entry)) { + throw new TypeError('Expected [K, V] tuple: ' + entry); + } + } + + function resolveSize(iter) { + assertNotInfinite(iter.size); + return ensureSize(iter); + } + + function iterableClass(iterable) { + return isKeyed(iterable) ? KeyedIterable : + isIndexed(iterable) ? IndexedIterable : + SetIterable; + } + + function makeSequence(iterable) { + return Object.create( + ( + isKeyed(iterable) ? KeyedSeq : + isIndexed(iterable) ? IndexedSeq : + SetSeq + ).prototype + ); + } + + function cacheResultThrough() { + if (this._iter.cacheResult) { + this._iter.cacheResult(); + this.size = this._iter.size; + return this; + } else { + return Seq.prototype.cacheResult.call(this); + } + } + + function defaultComparator(a, b) { + return a > b ? 1 : a < b ? -1 : 0; + } + + function forceIterator(keyPath) { + var iter = getIterator(keyPath); + if (!iter) { + // Array might not be iterable in this environment, so we need a fallback + // to our wrapped type. + if (!isArrayLike(keyPath)) { + throw new TypeError('Expected iterable or array-like: ' + keyPath); + } + iter = getIterator(Iterable(keyPath)); + } + return iter; + } + + createClass(Record, KeyedCollection); + + function Record(defaultValues, name) { + var hasInitialized; + + var RecordType = function Record(values) { + if (values instanceof RecordType) { + return values; + } + if (!(this instanceof RecordType)) { + return new RecordType(values); + } + if (!hasInitialized) { + hasInitialized = true; + var keys = Object.keys(defaultValues); + setProps(RecordTypePrototype, keys); + RecordTypePrototype.size = keys.length; + RecordTypePrototype._name = name; + RecordTypePrototype._keys = keys; + RecordTypePrototype._defaultValues = defaultValues; + } + this._map = Map(values); + }; + + var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype); + RecordTypePrototype.constructor = RecordType; + + return RecordType; + } + + Record.prototype.toString = function() { + return this.__toString(recordName(this) + ' {', '}'); + }; + + // @pragma Access + + Record.prototype.has = function(k) { + return this._defaultValues.hasOwnProperty(k); + }; + + Record.prototype.get = function(k, notSetValue) { + if (!this.has(k)) { + return notSetValue; + } + var defaultVal = this._defaultValues[k]; + return this._map ? this._map.get(k, defaultVal) : defaultVal; + }; + + // @pragma Modification + + Record.prototype.clear = function() { + if (this.__ownerID) { + this._map && this._map.clear(); + return this; + } + var RecordType = this.constructor; + return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap())); + }; + + Record.prototype.set = function(k, v) { + if (!this.has(k)) { + throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this)); + } + var newMap = this._map && this._map.set(k, v); + if (this.__ownerID || newMap === this._map) { + return this; + } + return makeRecord(this, newMap); + }; + + Record.prototype.remove = function(k) { + if (!this.has(k)) { + return this; + } + var newMap = this._map && this._map.remove(k); + if (this.__ownerID || newMap === this._map) { + return this; + } + return makeRecord(this, newMap); + }; + + Record.prototype.wasAltered = function() { + return this._map.wasAltered(); + }; + + Record.prototype.__iterator = function(type, reverse) {var this$0 = this; + return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse); + }; + + Record.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse); + }; + + Record.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + var newMap = this._map && this._map.__ensureOwner(ownerID); + if (!ownerID) { + this.__ownerID = ownerID; + this._map = newMap; + return this; + } + return makeRecord(this, newMap, ownerID); + }; + + + var RecordPrototype = Record.prototype; + RecordPrototype[DELETE] = RecordPrototype.remove; + RecordPrototype.deleteIn = + RecordPrototype.removeIn = MapPrototype.removeIn; + RecordPrototype.merge = MapPrototype.merge; + RecordPrototype.mergeWith = MapPrototype.mergeWith; + RecordPrototype.mergeIn = MapPrototype.mergeIn; + RecordPrototype.mergeDeep = MapPrototype.mergeDeep; + RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith; + RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; + RecordPrototype.setIn = MapPrototype.setIn; + RecordPrototype.update = MapPrototype.update; + RecordPrototype.updateIn = MapPrototype.updateIn; + RecordPrototype.withMutations = MapPrototype.withMutations; + RecordPrototype.asMutable = MapPrototype.asMutable; + RecordPrototype.asImmutable = MapPrototype.asImmutable; + + + function makeRecord(likeRecord, map, ownerID) { + var record = Object.create(Object.getPrototypeOf(likeRecord)); + record._map = map; + record.__ownerID = ownerID; + return record; + } + + function recordName(record) { + return record._name || record.constructor.name || 'Record'; + } + + function setProps(prototype, names) { + try { + names.forEach(setProp.bind(undefined, prototype)); + } catch (error) { + // Object.defineProperty failed. Probably IE8. + } + } + + function setProp(prototype, name) { + Object.defineProperty(prototype, name, { + get: function() { + return this.get(name); + }, + set: function(value) { + invariant(this.__ownerID, 'Cannot set on an immutable record.'); + this.set(name, value); + } + }); + } + + createClass(Set, SetCollection); + + // @pragma Construction + + function Set(value) { + return value === null || value === undefined ? emptySet() : + isSet(value) && !isOrdered(value) ? value : + emptySet().withMutations(function(set ) { + var iter = SetIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v ) {return set.add(v)}); + }); + } + + Set.of = function(/*...values*/) { + return this(arguments); + }; + + Set.fromKeys = function(value) { + return this(KeyedIterable(value).keySeq()); + }; + + Set.prototype.toString = function() { + return this.__toString('Set {', '}'); + }; + + // @pragma Access + + Set.prototype.has = function(value) { + return this._map.has(value); + }; + + // @pragma Modification + + Set.prototype.add = function(value) { + return updateSet(this, this._map.set(value, true)); + }; + + Set.prototype.remove = function(value) { + return updateSet(this, this._map.remove(value)); + }; + + Set.prototype.clear = function() { + return updateSet(this, this._map.clear()); + }; + + // @pragma Composition + + Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0); + iters = iters.filter(function(x ) {return x.size !== 0}); + if (iters.length === 0) { + return this; + } + if (this.size === 0 && !this.__ownerID && iters.length === 1) { + return this.constructor(iters[0]); + } + return this.withMutations(function(set ) { + for (var ii = 0; ii < iters.length; ii++) { + SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)}); + } + }); + }; + + Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0); + if (iters.length === 0) { + return this; + } + iters = iters.map(function(iter ) {return SetIterable(iter)}); + var originalSet = this; + return this.withMutations(function(set ) { + originalSet.forEach(function(value ) { + if (!iters.every(function(iter ) {return iter.includes(value)})) { + set.remove(value); + } + }); + }); + }; + + Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0); + if (iters.length === 0) { + return this; + } + iters = iters.map(function(iter ) {return SetIterable(iter)}); + var originalSet = this; + return this.withMutations(function(set ) { + originalSet.forEach(function(value ) { + if (iters.some(function(iter ) {return iter.includes(value)})) { + set.remove(value); + } + }); + }); + }; + + Set.prototype.merge = function() { + return this.union.apply(this, arguments); + }; + + Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return this.union.apply(this, iters); + }; + + Set.prototype.sort = function(comparator) { + // Late binding + return OrderedSet(sortFactory(this, comparator)); + }; + + Set.prototype.sortBy = function(mapper, comparator) { + // Late binding + return OrderedSet(sortFactory(this, comparator, mapper)); + }; + + Set.prototype.wasAltered = function() { + return this._map.wasAltered(); + }; + + Set.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse); + }; + + Set.prototype.__iterator = function(type, reverse) { + return this._map.map(function(_, k) {return k}).__iterator(type, reverse); + }; + + Set.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + var newMap = this._map.__ensureOwner(ownerID); + if (!ownerID) { + this.__ownerID = ownerID; + this._map = newMap; + return this; + } + return this.__make(newMap, ownerID); + }; + + + function isSet(maybeSet) { + return !!(maybeSet && maybeSet[IS_SET_SENTINEL]); + } + + Set.isSet = isSet; + + var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; + + var SetPrototype = Set.prototype; + SetPrototype[IS_SET_SENTINEL] = true; + SetPrototype[DELETE] = SetPrototype.remove; + SetPrototype.mergeDeep = SetPrototype.merge; + SetPrototype.mergeDeepWith = SetPrototype.mergeWith; + SetPrototype.withMutations = MapPrototype.withMutations; + SetPrototype.asMutable = MapPrototype.asMutable; + SetPrototype.asImmutable = MapPrototype.asImmutable; + + SetPrototype.__empty = emptySet; + SetPrototype.__make = makeSet; + + function updateSet(set, newMap) { + if (set.__ownerID) { + set.size = newMap.size; + set._map = newMap; + return set; + } + return newMap === set._map ? set : + newMap.size === 0 ? set.__empty() : + set.__make(newMap); + } + + function makeSet(map, ownerID) { + var set = Object.create(SetPrototype); + set.size = map ? map.size : 0; + set._map = map; + set.__ownerID = ownerID; + return set; + } + + var EMPTY_SET; + function emptySet() { + return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); + } + + createClass(OrderedSet, Set); + + // @pragma Construction + + function OrderedSet(value) { + return value === null || value === undefined ? emptyOrderedSet() : + isOrderedSet(value) ? value : + emptyOrderedSet().withMutations(function(set ) { + var iter = SetIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v ) {return set.add(v)}); + }); + } + + OrderedSet.of = function(/*...values*/) { + return this(arguments); + }; + + OrderedSet.fromKeys = function(value) { + return this(KeyedIterable(value).keySeq()); + }; + + OrderedSet.prototype.toString = function() { + return this.__toString('OrderedSet {', '}'); + }; + + + function isOrderedSet(maybeOrderedSet) { + return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); + } + + OrderedSet.isOrderedSet = isOrderedSet; + + var OrderedSetPrototype = OrderedSet.prototype; + OrderedSetPrototype[IS_ORDERED_SENTINEL] = true; + + OrderedSetPrototype.__empty = emptyOrderedSet; + OrderedSetPrototype.__make = makeOrderedSet; + + function makeOrderedSet(map, ownerID) { + var set = Object.create(OrderedSetPrototype); + set.size = map ? map.size : 0; + set._map = map; + set.__ownerID = ownerID; + return set; + } + + var EMPTY_ORDERED_SET; + function emptyOrderedSet() { + return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())); + } + + createClass(Stack, IndexedCollection); + + // @pragma Construction + + function Stack(value) { + return value === null || value === undefined ? emptyStack() : + isStack(value) ? value : + emptyStack().unshiftAll(value); + } + + Stack.of = function(/*...values*/) { + return this(arguments); + }; + + Stack.prototype.toString = function() { + return this.__toString('Stack [', ']'); + }; + + // @pragma Access + + Stack.prototype.get = function(index, notSetValue) { + var head = this._head; + index = wrapIndex(this, index); + while (head && index--) { + head = head.next; + } + return head ? head.value : notSetValue; + }; + + Stack.prototype.peek = function() { + return this._head && this._head.value; + }; + + // @pragma Modification + + Stack.prototype.push = function(/*...values*/) { + if (arguments.length === 0) { + return this; + } + var newSize = this.size + arguments.length; + var head = this._head; + for (var ii = arguments.length - 1; ii >= 0; ii--) { + head = { + value: arguments[ii], + next: head + }; + } + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; + + Stack.prototype.pushAll = function(iter) { + iter = IndexedIterable(iter); + if (iter.size === 0) { + return this; + } + assertNotInfinite(iter.size); + var newSize = this.size; + var head = this._head; + iter.reverse().forEach(function(value ) { + newSize++; + head = { + value: value, + next: head + }; + }); + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; + + Stack.prototype.pop = function() { + return this.slice(1); + }; + + Stack.prototype.unshift = function(/*...values*/) { + return this.push.apply(this, arguments); + }; + + Stack.prototype.unshiftAll = function(iter) { + return this.pushAll(iter); + }; + + Stack.prototype.shift = function() { + return this.pop.apply(this, arguments); + }; + + Stack.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._head = undefined; + this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyStack(); + }; + + Stack.prototype.slice = function(begin, end) { + if (wholeSlice(begin, end, this.size)) { + return this; + } + var resolvedBegin = resolveBegin(begin, this.size); + var resolvedEnd = resolveEnd(end, this.size); + if (resolvedEnd !== this.size) { + // super.slice(begin, end); + return IndexedCollection.prototype.slice.call(this, begin, end); + } + var newSize = this.size - resolvedBegin; + var head = this._head; + while (resolvedBegin--) { + head = head.next; + } + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; + + // @pragma Mutability + + Stack.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + this.__ownerID = ownerID; + this.__altered = false; + return this; + } + return makeStack(this.size, this._head, ownerID, this.__hash); + }; + + // @pragma Iteration + + Stack.prototype.__iterate = function(fn, reverse) { + if (reverse) { + return this.reverse().__iterate(fn); + } + var iterations = 0; + var node = this._head; + while (node) { + if (fn(node.value, iterations++, this) === false) { + break; + } + node = node.next; + } + return iterations; + }; + + Stack.prototype.__iterator = function(type, reverse) { + if (reverse) { + return this.reverse().__iterator(type); + } + var iterations = 0; + var node = this._head; + return new Iterator(function() { + if (node) { + var value = node.value; + node = node.next; + return iteratorValue(type, iterations++, value); + } + return iteratorDone(); + }); + }; + + + function isStack(maybeStack) { + return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]); + } + + Stack.isStack = isStack; + + var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; + + var StackPrototype = Stack.prototype; + StackPrototype[IS_STACK_SENTINEL] = true; + StackPrototype.withMutations = MapPrototype.withMutations; + StackPrototype.asMutable = MapPrototype.asMutable; + StackPrototype.asImmutable = MapPrototype.asImmutable; + StackPrototype.wasAltered = MapPrototype.wasAltered; + + + function makeStack(size, head, ownerID, hash) { + var map = Object.create(StackPrototype); + map.size = size; + map._head = head; + map.__ownerID = ownerID; + map.__hash = hash; + map.__altered = false; + return map; + } + + var EMPTY_STACK; + function emptyStack() { + return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); + } + + /** + * Contributes additional methods to a constructor + */ + function mixin(ctor, methods) { + var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; }; + Object.keys(methods).forEach(keyCopier); + Object.getOwnPropertySymbols && + Object.getOwnPropertySymbols(methods).forEach(keyCopier); + return ctor; + } + + Iterable.Iterator = Iterator; + + mixin(Iterable, { + + // ### Conversion to other types + + toArray: function() { + assertNotInfinite(this.size); + var array = new Array(this.size || 0); + this.valueSeq().__iterate(function(v, i) { array[i] = v; }); + return array; + }, + + toIndexedSeq: function() { + return new ToIndexedSequence(this); + }, + + toJS: function() { + return this.toSeq().map( + function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value} + ).__toJS(); + }, + + toJSON: function() { + return this.toSeq().map( + function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value} + ).__toJS(); + }, + + toKeyedSeq: function() { + return new ToKeyedSequence(this, true); + }, + + toMap: function() { + // Use Late Binding here to solve the circular dependency. + return Map(this.toKeyedSeq()); + }, + + toObject: function() { + assertNotInfinite(this.size); + var object = {}; + this.__iterate(function(v, k) { object[k] = v; }); + return object; + }, + + toOrderedMap: function() { + // Use Late Binding here to solve the circular dependency. + return OrderedMap(this.toKeyedSeq()); + }, + + toOrderedSet: function() { + // Use Late Binding here to solve the circular dependency. + return OrderedSet(isKeyed(this) ? this.valueSeq() : this); + }, + + toSet: function() { + // Use Late Binding here to solve the circular dependency. + return Set(isKeyed(this) ? this.valueSeq() : this); + }, + + toSetSeq: function() { + return new ToSetSequence(this); + }, + + toSeq: function() { + return isIndexed(this) ? this.toIndexedSeq() : + isKeyed(this) ? this.toKeyedSeq() : + this.toSetSeq(); + }, + + toStack: function() { + // Use Late Binding here to solve the circular dependency. + return Stack(isKeyed(this) ? this.valueSeq() : this); + }, + + toList: function() { + // Use Late Binding here to solve the circular dependency. + return List(isKeyed(this) ? this.valueSeq() : this); + }, + + + // ### Common JavaScript methods and properties + + toString: function() { + return '[Iterable]'; + }, + + __toString: function(head, tail) { + if (this.size === 0) { + return head + tail; + } + return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail; + }, + + + // ### ES6 Collection methods (ES6 Array and Map) + + concat: function() {var values = SLICE$0.call(arguments, 0); + return reify(this, concatFactory(this, values)); + }, + + includes: function(searchValue) { + return this.some(function(value ) {return is(value, searchValue)}); + }, + + entries: function() { + return this.__iterator(ITERATE_ENTRIES); + }, + + every: function(predicate, context) { + assertNotInfinite(this.size); + var returnValue = true; + this.__iterate(function(v, k, c) { + if (!predicate.call(context, v, k, c)) { + returnValue = false; + return false; + } + }); + return returnValue; + }, + + filter: function(predicate, context) { + return reify(this, filterFactory(this, predicate, context, true)); + }, + + find: function(predicate, context, notSetValue) { + var entry = this.findEntry(predicate, context); + return entry ? entry[1] : notSetValue; + }, + + findEntry: function(predicate, context) { + var found; + this.__iterate(function(v, k, c) { + if (predicate.call(context, v, k, c)) { + found = [k, v]; + return false; + } + }); + return found; + }, + + findLastEntry: function(predicate, context) { + return this.toSeq().reverse().findEntry(predicate, context); + }, + + forEach: function(sideEffect, context) { + assertNotInfinite(this.size); + return this.__iterate(context ? sideEffect.bind(context) : sideEffect); + }, + + join: function(separator) { + assertNotInfinite(this.size); + separator = separator !== undefined ? '' + separator : ','; + var joined = ''; + var isFirst = true; + this.__iterate(function(v ) { + isFirst ? (isFirst = false) : (joined += separator); + joined += v !== null && v !== undefined ? v.toString() : ''; + }); + return joined; + }, + + keys: function() { + return this.__iterator(ITERATE_KEYS); + }, + + map: function(mapper, context) { + return reify(this, mapFactory(this, mapper, context)); + }, + + reduce: function(reducer, initialReduction, context) { + assertNotInfinite(this.size); + var reduction; + var useFirst; + if (arguments.length < 2) { + useFirst = true; + } else { + reduction = initialReduction; + } + this.__iterate(function(v, k, c) { + if (useFirst) { + useFirst = false; + reduction = v; + } else { + reduction = reducer.call(context, reduction, v, k, c); + } + }); + return reduction; + }, + + reduceRight: function(reducer, initialReduction, context) { + var reversed = this.toKeyedSeq().reverse(); + return reversed.reduce.apply(reversed, arguments); + }, + + reverse: function() { + return reify(this, reverseFactory(this, true)); + }, + + slice: function(begin, end) { + return reify(this, sliceFactory(this, begin, end, true)); + }, + + some: function(predicate, context) { + return !this.every(not(predicate), context); + }, + + sort: function(comparator) { + return reify(this, sortFactory(this, comparator)); + }, + + values: function() { + return this.__iterator(ITERATE_VALUES); + }, + + + // ### More sequential methods + + butLast: function() { + return this.slice(0, -1); + }, + + isEmpty: function() { + return this.size !== undefined ? this.size === 0 : !this.some(function() {return true}); + }, + + count: function(predicate, context) { + return ensureSize( + predicate ? this.toSeq().filter(predicate, context) : this + ); + }, + + countBy: function(grouper, context) { + return countByFactory(this, grouper, context); + }, + + equals: function(other) { + return deepEqual(this, other); + }, + + entrySeq: function() { + var iterable = this; + if (iterable._cache) { + // We cache as an entries array, so we can just return the cache! + return new ArraySeq(iterable._cache); + } + var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq(); + entriesSequence.fromEntrySeq = function() {return iterable.toSeq()}; + return entriesSequence; + }, + + filterNot: function(predicate, context) { + return this.filter(not(predicate), context); + }, + + findLast: function(predicate, context, notSetValue) { + return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); + }, + + first: function() { + return this.find(returnTrue); + }, + + flatMap: function(mapper, context) { + return reify(this, flatMapFactory(this, mapper, context)); + }, + + flatten: function(depth) { + return reify(this, flattenFactory(this, depth, true)); + }, + + fromEntrySeq: function() { + return new FromEntriesSequence(this); + }, + + get: function(searchKey, notSetValue) { + return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue); + }, + + getIn: function(searchKeyPath, notSetValue) { + var nested = this; + // Note: in an ES6 environment, we would prefer: + // for (var key of searchKeyPath) { + var iter = forceIterator(searchKeyPath); + var step; + while (!(step = iter.next()).done) { + var key = step.value; + nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET; + if (nested === NOT_SET) { + return notSetValue; + } + } + return nested; + }, + + groupBy: function(grouper, context) { + return groupByFactory(this, grouper, context); + }, + + has: function(searchKey) { + return this.get(searchKey, NOT_SET) !== NOT_SET; + }, + + hasIn: function(searchKeyPath) { + return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET; + }, + + isSubset: function(iter) { + iter = typeof iter.includes === 'function' ? iter : Iterable(iter); + return this.every(function(value ) {return iter.includes(value)}); + }, + + isSuperset: function(iter) { + iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter); + return iter.isSubset(this); + }, + + keySeq: function() { + return this.toSeq().map(keyMapper).toIndexedSeq(); + }, + + last: function() { + return this.toSeq().reverse().first(); + }, + + max: function(comparator) { + return maxFactory(this, comparator); + }, + + maxBy: function(mapper, comparator) { + return maxFactory(this, comparator, mapper); + }, + + min: function(comparator) { + return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator); + }, + + minBy: function(mapper, comparator) { + return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper); + }, + + rest: function() { + return this.slice(1); + }, + + skip: function(amount) { + return this.slice(Math.max(0, amount)); + }, + + skipLast: function(amount) { + return reify(this, this.toSeq().reverse().skip(amount).reverse()); + }, + + skipWhile: function(predicate, context) { + return reify(this, skipWhileFactory(this, predicate, context, true)); + }, + + skipUntil: function(predicate, context) { + return this.skipWhile(not(predicate), context); + }, + + sortBy: function(mapper, comparator) { + return reify(this, sortFactory(this, comparator, mapper)); + }, + + take: function(amount) { + return this.slice(0, Math.max(0, amount)); + }, + + takeLast: function(amount) { + return reify(this, this.toSeq().reverse().take(amount).reverse()); + }, + + takeWhile: function(predicate, context) { + return reify(this, takeWhileFactory(this, predicate, context)); + }, + + takeUntil: function(predicate, context) { + return this.takeWhile(not(predicate), context); + }, + + valueSeq: function() { + return this.toIndexedSeq(); + }, + + + // ### Hashable Object + + hashCode: function() { + return this.__hash || (this.__hash = hashIterable(this)); + } + + + // ### Internal + + // abstract __iterate(fn, reverse) + + // abstract __iterator(type, reverse) + }); + + // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; + // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; + // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; + // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; + + var IterablePrototype = Iterable.prototype; + IterablePrototype[IS_ITERABLE_SENTINEL] = true; + IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values; + IterablePrototype.__toJS = IterablePrototype.toArray; + IterablePrototype.__toStringMapper = quoteString; + IterablePrototype.inspect = + IterablePrototype.toSource = function() { return this.toString(); }; + IterablePrototype.chain = IterablePrototype.flatMap; + IterablePrototype.contains = IterablePrototype.includes; + + // Temporary warning about using length + (function () { + try { + Object.defineProperty(IterablePrototype, 'length', { + get: function () { + if (!Iterable.noLengthWarning) { + var stack; + try { + throw new Error(); + } catch (error) { + stack = error.stack; + } + if (stack.indexOf('_wrapObject') === -1) { + console && console.warn && console.warn( + 'iterable.length has been deprecated, '+ + 'use iterable.size or iterable.count(). '+ + 'This warning will become a silent error in a future version. ' + + stack + ); + return this.size; + } + } + } + }); + } catch (e) {} + })(); + + + + mixin(KeyedIterable, { + + // ### More sequential methods + + flip: function() { + return reify(this, flipFactory(this)); + }, + + findKey: function(predicate, context) { + var entry = this.findEntry(predicate, context); + return entry && entry[0]; + }, + + findLastKey: function(predicate, context) { + return this.toSeq().reverse().findKey(predicate, context); + }, + + keyOf: function(searchValue) { + return this.findKey(function(value ) {return is(value, searchValue)}); + }, + + lastKeyOf: function(searchValue) { + return this.findLastKey(function(value ) {return is(value, searchValue)}); + }, + + mapEntries: function(mapper, context) {var this$0 = this; + var iterations = 0; + return reify(this, + this.toSeq().map( + function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)} + ).fromEntrySeq() + ); + }, + + mapKeys: function(mapper, context) {var this$0 = this; + return reify(this, + this.toSeq().flip().map( + function(k, v) {return mapper.call(context, k, v, this$0)} + ).flip() + ); + } + + }); + + var KeyedIterablePrototype = KeyedIterable.prototype; + KeyedIterablePrototype[IS_KEYED_SENTINEL] = true; + KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries; + KeyedIterablePrototype.__toJS = IterablePrototype.toObject; + KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)}; + + + + mixin(IndexedIterable, { + + // ### Conversion to other types + + toKeyedSeq: function() { + return new ToKeyedSequence(this, false); + }, + + + // ### ES6 Collection methods (ES6 Array and Map) + + filter: function(predicate, context) { + return reify(this, filterFactory(this, predicate, context, false)); + }, + + findIndex: function(predicate, context) { + var entry = this.findEntry(predicate, context); + return entry ? entry[0] : -1; + }, + + indexOf: function(searchValue) { + var key = this.toKeyedSeq().keyOf(searchValue); + return key === undefined ? -1 : key; + }, + + lastIndexOf: function(searchValue) { + var key = this.toKeyedSeq().reverse().keyOf(searchValue); + return key === undefined ? -1 : key; + + // var index = + // return this.toSeq().reverse().indexOf(searchValue); + }, + + reverse: function() { + return reify(this, reverseFactory(this, false)); + }, + + slice: function(begin, end) { + return reify(this, sliceFactory(this, begin, end, false)); + }, + + splice: function(index, removeNum /*, ...values*/) { + var numArgs = arguments.length; + removeNum = Math.max(removeNum | 0, 0); + if (numArgs === 0 || (numArgs === 2 && !removeNum)) { + return this; + } + // If index is negative, it should resolve relative to the size of the + // collection. However size may be expensive to compute if not cached, so + // only call count() if the number is in fact negative. + index = resolveBegin(index, index < 0 ? this.count() : this.size); + var spliced = this.slice(0, index); + return reify( + this, + numArgs === 1 ? + spliced : + spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)) + ); + }, + + + // ### More collection methods + + findLastIndex: function(predicate, context) { + var key = this.toKeyedSeq().findLastKey(predicate, context); + return key === undefined ? -1 : key; + }, + + first: function() { + return this.get(0); + }, + + flatten: function(depth) { + return reify(this, flattenFactory(this, depth, false)); + }, + + get: function(index, notSetValue) { + index = wrapIndex(this, index); + return (index < 0 || (this.size === Infinity || + (this.size !== undefined && index > this.size))) ? + notSetValue : + this.find(function(_, key) {return key === index}, undefined, notSetValue); + }, + + has: function(index) { + index = wrapIndex(this, index); + return index >= 0 && (this.size !== undefined ? + this.size === Infinity || index < this.size : + this.indexOf(index) !== -1 + ); + }, + + interpose: function(separator) { + return reify(this, interposeFactory(this, separator)); + }, + + interleave: function(/*...iterables*/) { + var iterables = [this].concat(arrCopy(arguments)); + var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables); + var interleaved = zipped.flatten(true); + if (zipped.size) { + interleaved.size = zipped.size * iterables.length; + } + return reify(this, interleaved); + }, + + last: function() { + return this.get(-1); + }, + + skipWhile: function(predicate, context) { + return reify(this, skipWhileFactory(this, predicate, context, false)); + }, + + zip: function(/*, ...iterables */) { + var iterables = [this].concat(arrCopy(arguments)); + return reify(this, zipWithFactory(this, defaultZipper, iterables)); + }, + + zipWith: function(zipper/*, ...iterables */) { + var iterables = arrCopy(arguments); + iterables[0] = this; + return reify(this, zipWithFactory(this, zipper, iterables)); + } + + }); + + IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true; + IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true; + + + + mixin(SetIterable, { + + // ### ES6 Collection methods (ES6 Array and Map) + + get: function(value, notSetValue) { + return this.has(value) ? value : notSetValue; + }, + + includes: function(value) { + return this.has(value); + }, + + + // ### More sequential methods + + keySeq: function() { + return this.valueSeq(); + } + + }); + + SetIterable.prototype.has = IterablePrototype.includes; + + + // Mixin subclasses + + mixin(KeyedSeq, KeyedIterable.prototype); + mixin(IndexedSeq, IndexedIterable.prototype); + mixin(SetSeq, SetIterable.prototype); + + mixin(KeyedCollection, KeyedIterable.prototype); + mixin(IndexedCollection, IndexedIterable.prototype); + mixin(SetCollection, SetIterable.prototype); + + + // #pragma Helper functions + + function keyMapper(v, k) { + return k; + } + + function entryMapper(v, k) { + return [k, v]; + } + + function not(predicate) { + return function() { + return !predicate.apply(this, arguments); + } + } + + function neg(predicate) { + return function() { + return -predicate.apply(this, arguments); + } + } + + function quoteString(value) { + return typeof value === 'string' ? JSON.stringify(value) : value; + } + + function defaultZipper() { + return arrCopy(arguments); + } + + function defaultNegComparator(a, b) { + return a < b ? 1 : a > b ? -1 : 0; + } + + function hashIterable(iterable) { + if (iterable.size === Infinity) { + return 0; + } + var ordered = isOrdered(iterable); + var keyed = isKeyed(iterable); + var h = ordered ? 1 : 0; + var size = iterable.__iterate( + keyed ? + ordered ? + function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } : + function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } : + ordered ? + function(v ) { h = 31 * h + hash(v) | 0; } : + function(v ) { h = h + hash(v) | 0; } + ); + return murmurHashOfSize(size, h); + } + + function murmurHashOfSize(size, h) { + h = imul(h, 0xCC9E2D51); + h = imul(h << 15 | h >>> -15, 0x1B873593); + h = imul(h << 13 | h >>> -13, 5); + h = (h + 0xE6546B64 | 0) ^ size; + h = imul(h ^ h >>> 16, 0x85EBCA6B); + h = imul(h ^ h >>> 13, 0xC2B2AE35); + h = smi(h ^ h >>> 16); + return h; + } + + function hashMerge(a, b) { + return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int + } + + var Immutable = { + + Iterable: Iterable, + + Seq: Seq, + Collection: Collection, + Map: Map, + OrderedMap: OrderedMap, + List: List, + Stack: Stack, + Set: Set, + OrderedSet: OrderedSet, + + Record: Record, + Range: Range, + Repeat: Repeat, + + is: is, + fromJS: fromJS + + }; + + return Immutable; + +})); + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + + + +/** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + +var validateFormat = function validateFormat(format) {}; + +if (process.env.NODE_ENV !== 'production') { + validateFormat = function validateFormat(format) { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + }; +} + +function invariant(condition, format, a, b, c, d, e, f) { + validateFormat(format); + + if (!condition) { + var error; + if (format === undefined) { + error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error(format.replace(/%s/g, function () { + return args[argIndex++]; + })); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } +} + +module.exports = invariant; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EditorState + * @format + * + */ + + + +var _assign = __webpack_require__(5); + +var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BlockTree = __webpack_require__(49); +var ContentState = __webpack_require__(29); +var EditorBidiService = __webpack_require__(115); +var Immutable = __webpack_require__(1); +var SelectionState = __webpack_require__(18); + +var OrderedSet = Immutable.OrderedSet, + Record = Immutable.Record, + Stack = Immutable.Stack; + + +var defaultRecord = { + allowUndo: true, + currentContent: null, + decorator: null, + directionMap: null, + forceSelection: false, + inCompositionMode: false, + inlineStyleOverride: null, + lastChangeType: null, + nativelyRenderedContent: null, + redoStack: Stack(), + selection: null, + treeMap: null, + undoStack: Stack() +}; + +var EditorStateRecord = Record(defaultRecord); + +var EditorState = function () { + EditorState.createEmpty = function createEmpty(decorator) { + return EditorState.createWithContent(ContentState.createFromText(''), decorator); + }; + + EditorState.createWithContent = function createWithContent(contentState, decorator) { + var firstKey = contentState.getBlockMap().first().getKey(); + return EditorState.create({ + currentContent: contentState, + undoStack: Stack(), + redoStack: Stack(), + decorator: decorator || null, + selection: SelectionState.createEmpty(firstKey) + }); + }; + + EditorState.create = function create(config) { + var currentContent = config.currentContent, + decorator = config.decorator; + + var recordConfig = _extends({}, config, { + treeMap: generateNewTreeMap(currentContent, decorator), + directionMap: EditorBidiService.getDirectionMap(currentContent) + }); + return new EditorState(new EditorStateRecord(recordConfig)); + }; + + EditorState.set = function set(editorState, put) { + var map = editorState.getImmutable().withMutations(function (state) { + var existingDecorator = state.get('decorator'); + var decorator = existingDecorator; + if (put.decorator === null) { + decorator = null; + } else if (put.decorator) { + decorator = put.decorator; + } + + var newContent = put.currentContent || editorState.getCurrentContent(); + + if (decorator !== existingDecorator) { + var treeMap = state.get('treeMap'); + var newTreeMap; + if (decorator && existingDecorator) { + newTreeMap = regenerateTreeForNewDecorator(newContent, newContent.getBlockMap(), treeMap, decorator, existingDecorator); + } else { + newTreeMap = generateNewTreeMap(newContent, decorator); + } + + state.merge({ + decorator: decorator, + treeMap: newTreeMap, + nativelyRenderedContent: null + }); + return; + } + + var existingContent = editorState.getCurrentContent(); + if (newContent !== existingContent) { + state.set('treeMap', regenerateTreeForNewBlocks(editorState, newContent.getBlockMap(), newContent.getEntityMap(), decorator)); + } + + state.merge(put); + }); + + return new EditorState(map); + }; + + EditorState.prototype.toJS = function toJS() { + return this.getImmutable().toJS(); + }; + + EditorState.prototype.getAllowUndo = function getAllowUndo() { + return this.getImmutable().get('allowUndo'); + }; + + EditorState.prototype.getCurrentContent = function getCurrentContent() { + return this.getImmutable().get('currentContent'); + }; + + EditorState.prototype.getUndoStack = function getUndoStack() { + return this.getImmutable().get('undoStack'); + }; + + EditorState.prototype.getRedoStack = function getRedoStack() { + return this.getImmutable().get('redoStack'); + }; + + EditorState.prototype.getSelection = function getSelection() { + return this.getImmutable().get('selection'); + }; + + EditorState.prototype.getDecorator = function getDecorator() { + return this.getImmutable().get('decorator'); + }; + + EditorState.prototype.isInCompositionMode = function isInCompositionMode() { + return this.getImmutable().get('inCompositionMode'); + }; + + EditorState.prototype.mustForceSelection = function mustForceSelection() { + return this.getImmutable().get('forceSelection'); + }; + + EditorState.prototype.getNativelyRenderedContent = function getNativelyRenderedContent() { + return this.getImmutable().get('nativelyRenderedContent'); + }; + + EditorState.prototype.getLastChangeType = function getLastChangeType() { + return this.getImmutable().get('lastChangeType'); + }; + + /** + * While editing, the user may apply inline style commands with a collapsed + * cursor, intending to type text that adopts the specified style. In this + * case, we track the specified style as an "override" that takes precedence + * over the inline style of the text adjacent to the cursor. + * + * If null, there is no override in place. + */ + + + EditorState.prototype.getInlineStyleOverride = function getInlineStyleOverride() { + return this.getImmutable().get('inlineStyleOverride'); + }; + + EditorState.setInlineStyleOverride = function setInlineStyleOverride(editorState, inlineStyleOverride) { + return EditorState.set(editorState, { inlineStyleOverride: inlineStyleOverride }); + }; + + /** + * Get the appropriate inline style for the editor state. If an + * override is in place, use it. Otherwise, the current style is + * based on the location of the selection state. + */ + + + EditorState.prototype.getCurrentInlineStyle = function getCurrentInlineStyle() { + var override = this.getInlineStyleOverride(); + if (override != null) { + return override; + } + + var content = this.getCurrentContent(); + var selection = this.getSelection(); + + if (selection.isCollapsed()) { + return getInlineStyleForCollapsedSelection(content, selection); + } + + return getInlineStyleForNonCollapsedSelection(content, selection); + }; + + EditorState.prototype.getBlockTree = function getBlockTree(blockKey) { + return this.getImmutable().getIn(['treeMap', blockKey]); + }; + + EditorState.prototype.isSelectionAtStartOfContent = function isSelectionAtStartOfContent() { + var firstKey = this.getCurrentContent().getBlockMap().first().getKey(); + return this.getSelection().hasEdgeWithin(firstKey, 0, 0); + }; + + EditorState.prototype.isSelectionAtEndOfContent = function isSelectionAtEndOfContent() { + var content = this.getCurrentContent(); + var blockMap = content.getBlockMap(); + var last = blockMap.last(); + var end = last.getLength(); + return this.getSelection().hasEdgeWithin(last.getKey(), end, end); + }; + + EditorState.prototype.getDirectionMap = function getDirectionMap() { + return this.getImmutable().get('directionMap'); + }; + + /** + * Incorporate native DOM selection changes into the EditorState. This + * method can be used when we simply want to accept whatever the DOM + * has given us to represent selection, and we do not need to re-render + * the editor. + * + * To forcibly move the DOM selection, see `EditorState.forceSelection`. + */ + + + EditorState.acceptSelection = function acceptSelection(editorState, selection) { + return updateSelection(editorState, selection, false); + }; + + /** + * At times, we need to force the DOM selection to be where we + * need it to be. This can occur when the anchor or focus nodes + * are non-text nodes, for instance. In this case, we want to trigger + * a re-render of the editor, which in turn forces selection into + * the correct place in the DOM. The `forceSelection` method + * accomplishes this. + * + * This method should be used in cases where you need to explicitly + * move the DOM selection from one place to another without a change + * in ContentState. + */ + + + EditorState.forceSelection = function forceSelection(editorState, selection) { + if (!selection.getHasFocus()) { + selection = selection.set('hasFocus', true); + } + return updateSelection(editorState, selection, true); + }; + + /** + * Move selection to the end of the editor without forcing focus. + */ + + + EditorState.moveSelectionToEnd = function moveSelectionToEnd(editorState) { + var content = editorState.getCurrentContent(); + var lastBlock = content.getLastBlock(); + var lastKey = lastBlock.getKey(); + var length = lastBlock.getLength(); + + return EditorState.acceptSelection(editorState, new SelectionState({ + anchorKey: lastKey, + anchorOffset: length, + focusKey: lastKey, + focusOffset: length, + isBackward: false + })); + }; + + /** + * Force focus to the end of the editor. This is useful in scenarios + * where we want to programmatically focus the input and it makes sense + * to allow the user to continue working seamlessly. + */ + + + EditorState.moveFocusToEnd = function moveFocusToEnd(editorState) { + var afterSelectionMove = EditorState.moveSelectionToEnd(editorState); + return EditorState.forceSelection(afterSelectionMove, afterSelectionMove.getSelection()); + }; + + /** + * Push the current ContentState onto the undo stack if it should be + * considered a boundary state, and set the provided ContentState as the + * new current content. + */ + + + EditorState.push = function push(editorState, contentState, changeType) { + if (editorState.getCurrentContent() === contentState) { + return editorState; + } + + var forceSelection = changeType !== 'insert-characters'; + var directionMap = EditorBidiService.getDirectionMap(contentState, editorState.getDirectionMap()); + + if (!editorState.getAllowUndo()) { + return EditorState.set(editorState, { + currentContent: contentState, + directionMap: directionMap, + lastChangeType: changeType, + selection: contentState.getSelectionAfter(), + forceSelection: forceSelection, + inlineStyleOverride: null + }); + } + + var selection = editorState.getSelection(); + var currentContent = editorState.getCurrentContent(); + var undoStack = editorState.getUndoStack(); + var newContent = contentState; + + if (selection !== currentContent.getSelectionAfter() || mustBecomeBoundary(editorState, changeType)) { + undoStack = undoStack.push(currentContent); + newContent = newContent.set('selectionBefore', selection); + } else if (changeType === 'insert-characters' || changeType === 'backspace-character' || changeType === 'delete-character') { + // Preserve the previous selection. + newContent = newContent.set('selectionBefore', currentContent.getSelectionBefore()); + } + + var inlineStyleOverride = editorState.getInlineStyleOverride(); + + // Don't discard inline style overrides for the following change types: + var overrideChangeTypes = ['adjust-depth', 'change-block-type', 'split-block']; + + if (overrideChangeTypes.indexOf(changeType) === -1) { + inlineStyleOverride = null; + } + + var editorStateChanges = { + currentContent: newContent, + directionMap: directionMap, + undoStack: undoStack, + redoStack: Stack(), + lastChangeType: changeType, + selection: contentState.getSelectionAfter(), + forceSelection: forceSelection, + inlineStyleOverride: inlineStyleOverride + }; + + return EditorState.set(editorState, editorStateChanges); + }; + + /** + * Make the top ContentState in the undo stack the new current content and + * push the current content onto the redo stack. + */ + + + EditorState.undo = function undo(editorState) { + if (!editorState.getAllowUndo()) { + return editorState; + } + + var undoStack = editorState.getUndoStack(); + var newCurrentContent = undoStack.peek(); + if (!newCurrentContent) { + return editorState; + } + + var currentContent = editorState.getCurrentContent(); + var directionMap = EditorBidiService.getDirectionMap(newCurrentContent, editorState.getDirectionMap()); + + return EditorState.set(editorState, { + currentContent: newCurrentContent, + directionMap: directionMap, + undoStack: undoStack.shift(), + redoStack: editorState.getRedoStack().push(currentContent), + forceSelection: true, + inlineStyleOverride: null, + lastChangeType: 'undo', + nativelyRenderedContent: null, + selection: currentContent.getSelectionBefore() + }); + }; + + /** + * Make the top ContentState in the redo stack the new current content and + * push the current content onto the undo stack. + */ + + + EditorState.redo = function redo(editorState) { + if (!editorState.getAllowUndo()) { + return editorState; + } + + var redoStack = editorState.getRedoStack(); + var newCurrentContent = redoStack.peek(); + if (!newCurrentContent) { + return editorState; + } + + var currentContent = editorState.getCurrentContent(); + var directionMap = EditorBidiService.getDirectionMap(newCurrentContent, editorState.getDirectionMap()); + + return EditorState.set(editorState, { + currentContent: newCurrentContent, + directionMap: directionMap, + undoStack: editorState.getUndoStack().push(currentContent), + redoStack: redoStack.shift(), + forceSelection: true, + inlineStyleOverride: null, + lastChangeType: 'redo', + nativelyRenderedContent: null, + selection: newCurrentContent.getSelectionAfter() + }); + }; + + /** + * Not for public consumption. + */ + + + function EditorState(immutable) { + _classCallCheck(this, EditorState); + + this._immutable = immutable; + } + + /** + * Not for public consumption. + */ + + + EditorState.prototype.getImmutable = function getImmutable() { + return this._immutable; + }; + + return EditorState; +}(); + +/** + * Set the supplied SelectionState as the new current selection, and set + * the `force` flag to trigger manual selection placement by the view. + */ + + +function updateSelection(editorState, selection, forceSelection) { + return EditorState.set(editorState, { + selection: selection, + forceSelection: forceSelection, + nativelyRenderedContent: null, + inlineStyleOverride: null + }); +} + +/** + * Regenerate the entire tree map for a given ContentState and decorator. + * Returns an OrderedMap that maps all available ContentBlock objects. + */ +function generateNewTreeMap(contentState, decorator) { + return contentState.getBlockMap().map(function (block) { + return BlockTree.generate(contentState, block, decorator); + }).toOrderedMap(); +} + +/** + * Regenerate tree map objects for all ContentBlocks that have changed + * between the current editorState and newContent. Returns an OrderedMap + * with only changed regenerated tree map objects. + */ +function regenerateTreeForNewBlocks(editorState, newBlockMap, newEntityMap, decorator) { + var contentState = editorState.getCurrentContent().set('entityMap', newEntityMap); + var prevBlockMap = contentState.getBlockMap(); + var prevTreeMap = editorState.getImmutable().get('treeMap'); + return prevTreeMap.merge(newBlockMap.toSeq().filter(function (block, key) { + return block !== prevBlockMap.get(key); + }).map(function (block) { + return BlockTree.generate(contentState, block, decorator); + })); +} + +/** + * Generate tree map objects for a new decorator object, preserving any + * decorations that are unchanged from the previous decorator. + * + * Note that in order for this to perform optimally, decoration Lists for + * decorators should be preserved when possible to allow for direct immutable + * List comparison. + */ +function regenerateTreeForNewDecorator(content, blockMap, previousTreeMap, decorator, existingDecorator) { + return previousTreeMap.merge(blockMap.toSeq().filter(function (block) { + return decorator.getDecorations(block, content) !== existingDecorator.getDecorations(block, content); + }).map(function (block) { + return BlockTree.generate(content, block, decorator); + })); +} + +/** + * Return whether a change should be considered a boundary state, given + * the previous change type. Allows us to discard potential boundary states + * during standard typing or deletion behavior. + */ +function mustBecomeBoundary(editorState, changeType) { + var lastChangeType = editorState.getLastChangeType(); + return changeType !== lastChangeType || changeType !== 'insert-characters' && changeType !== 'backspace-character' && changeType !== 'delete-character'; +} + +function getInlineStyleForCollapsedSelection(content, selection) { + var startKey = selection.getStartKey(); + var startOffset = selection.getStartOffset(); + var startBlock = content.getBlockForKey(startKey); + + // If the cursor is not at the start of the block, look backward to + // preserve the style of the preceding character. + if (startOffset > 0) { + return startBlock.getInlineStyleAt(startOffset - 1); + } + + // The caret is at position zero in this block. If the block has any + // text at all, use the style of the first character. + if (startBlock.getLength()) { + return startBlock.getInlineStyleAt(0); + } + + // Otherwise, look upward in the document to find the closest character. + return lookUpwardForInlineStyle(content, startKey); +} + +function getInlineStyleForNonCollapsedSelection(content, selection) { + var startKey = selection.getStartKey(); + var startOffset = selection.getStartOffset(); + var startBlock = content.getBlockForKey(startKey); + + // If there is a character just inside the selection, use its style. + if (startOffset < startBlock.getLength()) { + return startBlock.getInlineStyleAt(startOffset); + } + + // Check if the selection at the end of a non-empty block. Use the last + // style in the block. + if (startOffset > 0) { + return startBlock.getInlineStyleAt(startOffset - 1); + } + + // Otherwise, look upward in the document to find the closest character. + return lookUpwardForInlineStyle(content, startKey); +} + +function lookUpwardForInlineStyle(content, fromKey) { + var lastNonEmpty = content.getBlockMap().reverse().skipUntil(function (_, k) { + return k === fromKey; + }).skip(1).skipUntil(function (block, _) { + return block.getLength(); + }).first(); + + if (lastNonEmpty) return lastNonEmpty.getInlineStyleAt(lastNonEmpty.getLength() - 1); + return OrderedSet(); +} + +module.exports = EditorState; + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) { + +if (process.env.NODE_ENV === 'production') { + module.exports = __webpack_require__(206); +} else { + module.exports = __webpack_require__(205); +} + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + + +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftModifier + * @format + * + */ + + + +var CharacterMetadata = __webpack_require__(7); +var ContentStateInlineStyle = __webpack_require__(100); +var DraftFeatureFlags = __webpack_require__(14); +var Immutable = __webpack_require__(1); + +var applyEntityToContentState = __webpack_require__(119); +var getCharacterRemovalRange = __webpack_require__(140); +var getContentStateFragment = __webpack_require__(27); +var insertFragmentIntoContentState = __webpack_require__(145); +var insertTextIntoContentState = __webpack_require__(146); +var invariant = __webpack_require__(2); +var modifyBlockForContentState = __webpack_require__(157); +var removeEntitiesAtEdges = __webpack_require__(71); +var removeRangeFromContentState = __webpack_require__(159); +var splitBlockInContentState = __webpack_require__(161); + +var OrderedSet = Immutable.OrderedSet; + +/** + * `DraftModifier` provides a set of convenience methods that apply + * modifications to a `ContentState` object based on a target `SelectionState`. + * + * Any change to a `ContentState` should be decomposable into a series of + * transaction functions that apply the required changes and return output + * `ContentState` objects. + * + * These functions encapsulate some of the most common transaction sequences. + */ + +var DraftModifier = { + replaceText: function replaceText(contentState, rangeToReplace, text, inlineStyle, entityKey) { + var withoutEntities = removeEntitiesAtEdges(contentState, rangeToReplace); + var withoutText = removeRangeFromContentState(withoutEntities, rangeToReplace); + + var character = CharacterMetadata.create({ + style: inlineStyle || OrderedSet(), + entity: entityKey || null + }); + + return insertTextIntoContentState(withoutText, withoutText.getSelectionAfter(), text, character); + }, + + insertText: function insertText(contentState, targetRange, text, inlineStyle, entityKey) { + !targetRange.isCollapsed() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Target range must be collapsed for `insertText`.') : invariant(false) : void 0; + return DraftModifier.replaceText(contentState, targetRange, text, inlineStyle, entityKey); + }, + + moveText: function moveText(contentState, removalRange, targetRange) { + var movedFragment = getContentStateFragment(contentState, removalRange); + + var afterRemoval = DraftModifier.removeRange(contentState, removalRange, 'backward'); + + return DraftModifier.replaceWithFragment(afterRemoval, targetRange, movedFragment); + }, + + replaceWithFragment: function replaceWithFragment(contentState, targetRange, fragment) { + var withoutEntities = removeEntitiesAtEdges(contentState, targetRange); + var withoutText = removeRangeFromContentState(withoutEntities, targetRange); + + return insertFragmentIntoContentState(withoutText, withoutText.getSelectionAfter(), fragment); + }, + + removeRange: function removeRange(contentState, rangeToRemove, removalDirection) { + var startKey = void 0, + endKey = void 0, + startBlock = void 0, + endBlock = void 0; + if (rangeToRemove.getIsBackward()) { + rangeToRemove = rangeToRemove.merge({ + anchorKey: rangeToRemove.getFocusKey(), + anchorOffset: rangeToRemove.getFocusOffset(), + focusKey: rangeToRemove.getAnchorKey(), + focusOffset: rangeToRemove.getAnchorOffset(), + isBackward: false + }); + } + startKey = rangeToRemove.getAnchorKey(); + endKey = rangeToRemove.getFocusKey(); + startBlock = contentState.getBlockForKey(startKey); + endBlock = contentState.getBlockForKey(endKey); + var startOffset = rangeToRemove.getStartOffset(); + var endOffset = rangeToRemove.getEndOffset(); + + var startEntityKey = startBlock.getEntityAt(startOffset); + var endEntityKey = endBlock.getEntityAt(endOffset - 1); + + // Check whether the selection state overlaps with a single entity. + // If so, try to remove the appropriate substring of the entity text. + if (startKey === endKey) { + if (startEntityKey && startEntityKey === endEntityKey) { + var _adjustedRemovalRange = getCharacterRemovalRange(contentState.getEntityMap(), startBlock, endBlock, rangeToRemove, removalDirection); + return removeRangeFromContentState(contentState, _adjustedRemovalRange); + } + } + var adjustedRemovalRange = rangeToRemove; + if (DraftFeatureFlags.draft_segmented_entities_behavior) { + // Adjust the selection to properly delete segemented and immutable + // entities + adjustedRemovalRange = getCharacterRemovalRange(contentState.getEntityMap(), startBlock, endBlock, rangeToRemove, removalDirection); + } + + var withoutEntities = removeEntitiesAtEdges(contentState, adjustedRemovalRange); + return removeRangeFromContentState(withoutEntities, adjustedRemovalRange); + }, + + splitBlock: function splitBlock(contentState, selectionState) { + var withoutEntities = removeEntitiesAtEdges(contentState, selectionState); + var withoutText = removeRangeFromContentState(withoutEntities, selectionState); + + return splitBlockInContentState(withoutText, withoutText.getSelectionAfter()); + }, + + applyInlineStyle: function applyInlineStyle(contentState, selectionState, inlineStyle) { + return ContentStateInlineStyle.add(contentState, selectionState, inlineStyle); + }, + + removeInlineStyle: function removeInlineStyle(contentState, selectionState, inlineStyle) { + return ContentStateInlineStyle.remove(contentState, selectionState, inlineStyle); + }, + + setBlockType: function setBlockType(contentState, selectionState, blockType) { + return modifyBlockForContentState(contentState, selectionState, function (block) { + return block.merge({ type: blockType, depth: 0 }); + }); + }, + + setBlockData: function setBlockData(contentState, selectionState, blockData) { + return modifyBlockForContentState(contentState, selectionState, function (block) { + return block.merge({ data: blockData }); + }); + }, + + mergeBlockData: function mergeBlockData(contentState, selectionState, blockData) { + return modifyBlockForContentState(contentState, selectionState, function (block) { + return block.merge({ data: block.getData().merge(blockData) }); + }); + }, + + applyEntity: function applyEntity(contentState, selectionState, entityKey) { + var withoutEntities = removeEntitiesAtEdges(contentState, selectionState); + return applyEntityToContentState(withoutEntities, selectionState, entityKey); + } +}; + +module.exports = DraftModifier; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule CharacterMetadata + * @format + * + */ + + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _require = __webpack_require__(1), + Map = _require.Map, + OrderedSet = _require.OrderedSet, + Record = _require.Record; + +// Immutable.map is typed such that the value for every key in the map +// must be the same type + + +var EMPTY_SET = OrderedSet(); + +var defaultRecord = { + style: EMPTY_SET, + entity: null +}; + +var CharacterMetadataRecord = Record(defaultRecord); + +var CharacterMetadata = function (_CharacterMetadataRec) { + _inherits(CharacterMetadata, _CharacterMetadataRec); + + function CharacterMetadata() { + _classCallCheck(this, CharacterMetadata); + + return _possibleConstructorReturn(this, _CharacterMetadataRec.apply(this, arguments)); + } + + CharacterMetadata.prototype.getStyle = function getStyle() { + return this.get('style'); + }; + + CharacterMetadata.prototype.getEntity = function getEntity() { + return this.get('entity'); + }; + + CharacterMetadata.prototype.hasStyle = function hasStyle(style) { + return this.getStyle().includes(style); + }; + + CharacterMetadata.applyStyle = function applyStyle(record, style) { + var withStyle = record.set('style', record.getStyle().add(style)); + return CharacterMetadata.create(withStyle); + }; + + CharacterMetadata.removeStyle = function removeStyle(record, style) { + var withoutStyle = record.set('style', record.getStyle().remove(style)); + return CharacterMetadata.create(withoutStyle); + }; + + CharacterMetadata.applyEntity = function applyEntity(record, entityKey) { + var withEntity = record.getEntity() === entityKey ? record : record.set('entity', entityKey); + return CharacterMetadata.create(withEntity); + }; + + /** + * Use this function instead of the `CharacterMetadata` constructor. + * Since most content generally uses only a very small number of + * style/entity permutations, we can reuse these objects as often as + * possible. + */ + + + CharacterMetadata.create = function create(config) { + if (!config) { + return EMPTY; + } + + var defaultConfig = { + style: EMPTY_SET, + entity: null + }; + + // Fill in unspecified properties, if necessary. + var configMap = Map(defaultConfig).merge(config); + + var existing = pool.get(configMap); + if (existing) { + return existing; + } + + var newCharacter = new CharacterMetadata(configMap); + pool = pool.set(configMap, newCharacter); + return newCharacter; + }; + + return CharacterMetadata; +}(CharacterMetadataRecord); + +var EMPTY = new CharacterMetadata(); +var pool = Map([[Map(defaultRecord), EMPTY]]); + +CharacterMetadata.EMPTY = EMPTY; + +module.exports = CharacterMetadata; + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +if (process.env.NODE_ENV !== 'production') { + var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && + Symbol.for && + Symbol.for('react.element')) || + 0xeac7; + + var isValidElement = function(object) { + return typeof object === 'object' && + object !== null && + object.$$typeof === REACT_ELEMENT_TYPE; + }; + + // By explicitly using `prop-types` you are opting into new development behavior. + // http://fb.me/prop-types-in-prod + var throwOnDirectAccess = true; + module.exports = __webpack_require__(185)(isValidElement, throwOnDirectAccess); +} else { + // By explicitly using `prop-types` you are opting into new production behavior. + // http://fb.me/prop-types-in-prod + module.exports = __webpack_require__(184)(); +} + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ContentBlockNode + * @format + * + * + * This file is a fork of ContentBlock adding support for nesting references by + * providing links to children, parent, prevSibling, and nextSibling. + * + * This is unstable and not part of the public API and should not be used by + * production systems. This file may be update/removed without notice. + */ + + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CharacterMetadata = __webpack_require__(7); +var Immutable = __webpack_require__(1); + +var findRangesImmutable = __webpack_require__(21); + +var List = Immutable.List, + Map = Immutable.Map, + OrderedSet = Immutable.OrderedSet, + Record = Immutable.Record, + Repeat = Immutable.Repeat; + + +var EMPTY_SET = OrderedSet(); + +var defaultRecord = { + parent: null, + characterList: List(), + data: Map(), + depth: 0, + key: '', + text: '', + type: 'unstyled', + children: List(), + prevSibling: null, + nextSibling: null +}; + +var haveEqualStyle = function haveEqualStyle(charA, charB) { + return charA.getStyle() === charB.getStyle(); +}; + +var haveEqualEntity = function haveEqualEntity(charA, charB) { + return charA.getEntity() === charB.getEntity(); +}; + +var decorateCharacterList = function decorateCharacterList(config) { + if (!config) { + return config; + } + + var characterList = config.characterList, + text = config.text; + + + if (text && !characterList) { + config.characterList = List(Repeat(CharacterMetadata.EMPTY, text.length)); + } + + return config; +}; + +var ContentBlockNode = function (_Record) { + _inherits(ContentBlockNode, _Record); + + function ContentBlockNode() { + var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultRecord; + + _classCallCheck(this, ContentBlockNode); + + return _possibleConstructorReturn(this, _Record.call(this, decorateCharacterList(props))); + } + + ContentBlockNode.prototype.getKey = function getKey() { + return this.get('key'); + }; + + ContentBlockNode.prototype.getType = function getType() { + return this.get('type'); + }; + + ContentBlockNode.prototype.getText = function getText() { + return this.get('text'); + }; + + ContentBlockNode.prototype.getCharacterList = function getCharacterList() { + return this.get('characterList'); + }; + + ContentBlockNode.prototype.getLength = function getLength() { + return this.getText().length; + }; + + ContentBlockNode.prototype.getDepth = function getDepth() { + return this.get('depth'); + }; + + ContentBlockNode.prototype.getData = function getData() { + return this.get('data'); + }; + + ContentBlockNode.prototype.getInlineStyleAt = function getInlineStyleAt(offset) { + var character = this.getCharacterList().get(offset); + return character ? character.getStyle() : EMPTY_SET; + }; + + ContentBlockNode.prototype.getEntityAt = function getEntityAt(offset) { + var character = this.getCharacterList().get(offset); + return character ? character.getEntity() : null; + }; + + ContentBlockNode.prototype.getChildKeys = function getChildKeys() { + return this.get('children'); + }; + + ContentBlockNode.prototype.getParentKey = function getParentKey() { + return this.get('parent'); + }; + + ContentBlockNode.prototype.getPrevSiblingKey = function getPrevSiblingKey() { + return this.get('prevSibling'); + }; + + ContentBlockNode.prototype.getNextSiblingKey = function getNextSiblingKey() { + return this.get('nextSibling'); + }; + + ContentBlockNode.prototype.findStyleRanges = function findStyleRanges(filterFn, callback) { + findRangesImmutable(this.getCharacterList(), haveEqualStyle, filterFn, callback); + }; + + ContentBlockNode.prototype.findEntityRanges = function findEntityRanges(filterFn, callback) { + findRangesImmutable(this.getCharacterList(), haveEqualEntity, filterFn, callback); + }; + + return ContentBlockNode; +}(Record(defaultRecord)); + +module.exports = ContentBlockNode; + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + */ + +var nullthrows = function nullthrows(x) { + if (x != null) { + return x; + } + throw new Error("Got unexpected null or undefined"); +}; + +module.exports = nullthrows; + +/***/ }), +/* 11 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + + + +var UserAgentData = __webpack_require__(167); +var VersionRange = __webpack_require__(168); + +var mapObject = __webpack_require__(181); +var memoizeStringOnly = __webpack_require__(182); + +/** + * Checks to see whether `name` and `version` satisfy `query`. + * + * @param {string} name Name of the browser, device, engine or platform + * @param {?string} version Version of the browser, engine or platform + * @param {string} query Query of form "Name [range expression]" + * @param {?function} normalizer Optional pre-processor for range expression + * @return {boolean} + */ +function compare(name, version, query, normalizer) { + // check for exact match with no version + if (name === query) { + return true; + } + + // check for non-matching names + if (!query.startsWith(name)) { + return false; + } + + // full comparison with version + var range = query.slice(name.length); + if (version) { + range = normalizer ? normalizer(range) : range; + return VersionRange.contains(range, version); + } + + return false; +} + +/** + * Normalizes `version` by stripping any "NT" prefix, but only on the Windows + * platform. + * + * Mimics the stripping performed by the `UserAgentWindowsPlatform` PHP class. + * + * @param {string} version + * @return {string} + */ +function normalizePlatformVersion(version) { + if (UserAgentData.platformName === 'Windows') { + return version.replace(/^\s*NT/, ''); + } + + return version; +} + +/** + * Provides client-side access to the authoritative PHP-generated User Agent + * information supplied by the server. + */ +var UserAgent = { + /** + * Check if the User Agent browser matches `query`. + * + * `query` should be a string like "Chrome" or "Chrome > 33". + * + * Valid browser names include: + * + * - ACCESS NetFront + * - AOL + * - Amazon Silk + * - Android + * - BlackBerry + * - BlackBerry PlayBook + * - Chrome + * - Chrome for iOS + * - Chrome frame + * - Facebook PHP SDK + * - Facebook for iOS + * - Firefox + * - IE + * - IE Mobile + * - Mobile Safari + * - Motorola Internet Browser + * - Nokia + * - Openwave Mobile Browser + * - Opera + * - Opera Mini + * - Opera Mobile + * - Safari + * - UIWebView + * - Unknown + * - webOS + * - etc... + * + * An authoritative list can be found in the PHP `BrowserDetector` class and + * related classes in the same file (see calls to `new UserAgentBrowser` here: + * https://fburl.com/50728104). + * + * @note Function results are memoized + * + * @param {string} query Query of the form "Name [range expression]" + * @return {boolean} + */ + isBrowser: function isBrowser(query) { + return compare(UserAgentData.browserName, UserAgentData.browserFullVersion, query); + }, + + + /** + * Check if the User Agent browser uses a 32 or 64 bit architecture. + * + * @note Function results are memoized + * + * @param {string} query Query of the form "32" or "64". + * @return {boolean} + */ + isBrowserArchitecture: function isBrowserArchitecture(query) { + return compare(UserAgentData.browserArchitecture, null, query); + }, + + + /** + * Check if the User Agent device matches `query`. + * + * `query` should be a string like "iPhone" or "iPad". + * + * Valid device names include: + * + * - Kindle + * - Kindle Fire + * - Unknown + * - iPad + * - iPhone + * - iPod + * - etc... + * + * An authoritative list can be found in the PHP `DeviceDetector` class and + * related classes in the same file (see calls to `new UserAgentDevice` here: + * https://fburl.com/50728332). + * + * @note Function results are memoized + * + * @param {string} query Query of the form "Name" + * @return {boolean} + */ + isDevice: function isDevice(query) { + return compare(UserAgentData.deviceName, null, query); + }, + + + /** + * Check if the User Agent rendering engine matches `query`. + * + * `query` should be a string like "WebKit" or "WebKit >= 537". + * + * Valid engine names include: + * + * - Gecko + * - Presto + * - Trident + * - WebKit + * - etc... + * + * An authoritative list can be found in the PHP `RenderingEngineDetector` + * class related classes in the same file (see calls to `new + * UserAgentRenderingEngine` here: https://fburl.com/50728617). + * + * @note Function results are memoized + * + * @param {string} query Query of the form "Name [range expression]" + * @return {boolean} + */ + isEngine: function isEngine(query) { + return compare(UserAgentData.engineName, UserAgentData.engineVersion, query); + }, + + + /** + * Check if the User Agent platform matches `query`. + * + * `query` should be a string like "Windows" or "iOS 5 - 6". + * + * Valid platform names include: + * + * - Android + * - BlackBerry OS + * - Java ME + * - Linux + * - Mac OS X + * - Mac OS X Calendar + * - Mac OS X Internet Account + * - Symbian + * - SymbianOS + * - Windows + * - Windows Mobile + * - Windows Phone + * - iOS + * - iOS Facebook Integration Account + * - iOS Facebook Social Sharing UI + * - webOS + * - Chrome OS + * - etc... + * + * An authoritative list can be found in the PHP `PlatformDetector` class and + * related classes in the same file (see calls to `new UserAgentPlatform` + * here: https://fburl.com/50729226). + * + * @note Function results are memoized + * + * @param {string} query Query of the form "Name [range expression]" + * @return {boolean} + */ + isPlatform: function isPlatform(query) { + return compare(UserAgentData.platformName, UserAgentData.platformFullVersion, query, normalizePlatformVersion); + }, + + + /** + * Check if the User Agent platform is a 32 or 64 bit architecture. + * + * @note Function results are memoized + * + * @param {string} query Query of the form "32" or "64". + * @return {boolean} + */ + isPlatformArchitecture: function isPlatformArchitecture(query) { + return compare(UserAgentData.platformArchitecture, null, query); + } +}; + +module.exports = mapObject(UserAgent, memoizeStringOnly); + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule generateRandomKey + * @format + * + */ + + + +var seenKeys = {}; +var MULTIPLIER = Math.pow(2, 24); + +function generateRandomKey() { + var key = void 0; + while (key === undefined || seenKeys.hasOwnProperty(key) || !isNaN(+key)) { + key = Math.floor(Math.random() * MULTIPLIER).toString(32); + } + seenKeys[key] = true; + return key; +} + +module.exports = generateRandomKey; + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftFeatureFlags + * @format + * + */ + + + +var DraftFeatureFlags = __webpack_require__(111); + +module.exports = DraftFeatureFlags; + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ContentBlock + * @format + * + */ + + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CharacterMetadata = __webpack_require__(7); +var Immutable = __webpack_require__(1); + +var findRangesImmutable = __webpack_require__(21); + +var List = Immutable.List, + Map = Immutable.Map, + OrderedSet = Immutable.OrderedSet, + Record = Immutable.Record, + Repeat = Immutable.Repeat; + + +var EMPTY_SET = OrderedSet(); + +var defaultRecord = { + key: '', + type: 'unstyled', + text: '', + characterList: List(), + depth: 0, + data: Map() +}; + +var ContentBlockRecord = Record(defaultRecord); + +var decorateCharacterList = function decorateCharacterList(config) { + if (!config) { + return config; + } + + var characterList = config.characterList, + text = config.text; + + + if (text && !characterList) { + config.characterList = List(Repeat(CharacterMetadata.EMPTY, text.length)); + } + + return config; +}; + +var ContentBlock = function (_ContentBlockRecord) { + _inherits(ContentBlock, _ContentBlockRecord); + + function ContentBlock(config) { + _classCallCheck(this, ContentBlock); + + return _possibleConstructorReturn(this, _ContentBlockRecord.call(this, decorateCharacterList(config))); + } + + ContentBlock.prototype.getKey = function getKey() { + return this.get('key'); + }; + + ContentBlock.prototype.getType = function getType() { + return this.get('type'); + }; + + ContentBlock.prototype.getText = function getText() { + return this.get('text'); + }; + + ContentBlock.prototype.getCharacterList = function getCharacterList() { + return this.get('characterList'); + }; + + ContentBlock.prototype.getLength = function getLength() { + return this.getText().length; + }; + + ContentBlock.prototype.getDepth = function getDepth() { + return this.get('depth'); + }; + + ContentBlock.prototype.getData = function getData() { + return this.get('data'); + }; + + ContentBlock.prototype.getInlineStyleAt = function getInlineStyleAt(offset) { + var character = this.getCharacterList().get(offset); + return character ? character.getStyle() : EMPTY_SET; + }; + + ContentBlock.prototype.getEntityAt = function getEntityAt(offset) { + var character = this.getCharacterList().get(offset); + return character ? character.getEntity() : null; + }; + + /** + * Execute a callback for every contiguous range of styles within the block. + */ + + + ContentBlock.prototype.findStyleRanges = function findStyleRanges(filterFn, callback) { + findRangesImmutable(this.getCharacterList(), haveEqualStyle, filterFn, callback); + }; + + /** + * Execute a callback for every contiguous range of entities within the block. + */ + + + ContentBlock.prototype.findEntityRanges = function findEntityRanges(filterFn, callback) { + findRangesImmutable(this.getCharacterList(), haveEqualEntity, filterFn, callback); + }; + + return ContentBlock; +}(ContentBlockRecord); + +function haveEqualStyle(charA, charB) { + return charA.getStyle() === charB.getStyle(); +} + +function haveEqualEntity(charA, charB) { + return charA.getEntity() === charB.getEntity(); +} + +module.exports = ContentBlock; + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +/** + * Unicode-enabled replacesments for basic String functions. + * + * All the functions in this module assume that the input string is a valid + * UTF-16 encoding of a Unicode sequence. If it's not the case, the behavior + * will be undefined. + * + * WARNING: Since this module is typechecks-enforced, you may find new bugs + * when replacing normal String functions with ones provided here. + */ + + + +var invariant = __webpack_require__(2); + +// These two ranges are consecutive so anything in [HIGH_START, LOW_END] is a +// surrogate code unit. +var SURROGATE_HIGH_START = 0xD800; +var SURROGATE_HIGH_END = 0xDBFF; +var SURROGATE_LOW_START = 0xDC00; +var SURROGATE_LOW_END = 0xDFFF; +var SURROGATE_UNITS_REGEX = /[\uD800-\uDFFF]/; + +/** + * @param {number} codeUnit A Unicode code-unit, in range [0, 0x10FFFF] + * @return {boolean} Whether code-unit is in a surrogate (hi/low) range + */ +function isCodeUnitInSurrogateRange(codeUnit) { + return SURROGATE_HIGH_START <= codeUnit && codeUnit <= SURROGATE_LOW_END; +} + +/** + * Returns whether the two characters starting at `index` form a surrogate pair. + * For example, given the string s = "\uD83D\uDE0A", (s, 0) returns true and + * (s, 1) returns false. + * + * @param {string} str + * @param {number} index + * @return {boolean} + */ +function isSurrogatePair(str, index) { + !(0 <= index && index < str.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isSurrogatePair: Invalid index %s for string length %s.', index, str.length) : invariant(false) : void 0; + if (index + 1 === str.length) { + return false; + } + var first = str.charCodeAt(index); + var second = str.charCodeAt(index + 1); + return SURROGATE_HIGH_START <= first && first <= SURROGATE_HIGH_END && SURROGATE_LOW_START <= second && second <= SURROGATE_LOW_END; +} + +/** + * @param {string} str Non-empty string + * @return {boolean} True if the input includes any surrogate code units + */ +function hasSurrogateUnit(str) { + return SURROGATE_UNITS_REGEX.test(str); +} + +/** + * Return the length of the original Unicode character at given position in the + * String by looking into the UTF-16 code unit; that is equal to 1 for any + * non-surrogate characters in BMP ([U+0000..U+D7FF] and [U+E000, U+FFFF]); and + * returns 2 for the hi/low surrogates ([U+D800..U+DFFF]), which are in fact + * representing non-BMP characters ([U+10000..U+10FFFF]). + * + * Examples: + * - '\u0020' => 1 + * - '\u3020' => 1 + * - '\uD835' => 2 + * - '\uD835\uDDEF' => 2 + * - '\uDDEF' => 2 + * + * @param {string} str Non-empty string + * @param {number} pos Position in the string to look for one code unit + * @return {number} Number 1 or 2 + */ +function getUTF16Length(str, pos) { + return 1 + isCodeUnitInSurrogateRange(str.charCodeAt(pos)); +} + +/** + * Fully Unicode-enabled replacement for String#length + * + * @param {string} str Valid Unicode string + * @return {number} The number of Unicode characters in the string + */ +function strlen(str) { + // Call the native functions if there's no surrogate char + if (!hasSurrogateUnit(str)) { + return str.length; + } + + var len = 0; + for (var pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) { + len++; + } + return len; +} + +/** + * Fully Unicode-enabled replacement for String#substr() + * + * @param {string} str Valid Unicode string + * @param {number} start Location in Unicode sequence to begin extracting + * @param {?number} length The number of Unicode characters to extract + * (default: to the end of the string) + * @return {string} Extracted sub-string + */ +function substr(str, start, length) { + start = start || 0; + length = length === undefined ? Infinity : length || 0; + + // Call the native functions if there's no surrogate char + if (!hasSurrogateUnit(str)) { + return str.substr(start, length); + } + + // Obvious cases + var size = str.length; + if (size <= 0 || start > size || length <= 0) { + return ''; + } + + // Find the actual starting position + var posA = 0; + if (start > 0) { + for (; start > 0 && posA < size; start--) { + posA += getUTF16Length(str, posA); + } + if (posA >= size) { + return ''; + } + } else if (start < 0) { + for (posA = size; start < 0 && 0 < posA; start++) { + posA -= getUTF16Length(str, posA - 1); + } + if (posA < 0) { + posA = 0; + } + } + + // Find the actual ending position + var posB = size; + if (length < size) { + for (posB = posA; length > 0 && posB < size; length--) { + posB += getUTF16Length(str, posB); + } + } + + return str.substring(posA, posB); +} + +/** + * Fully Unicode-enabled replacement for String#substring() + * + * @param {string} str Valid Unicode string + * @param {number} start Location in Unicode sequence to begin extracting + * @param {?number} end Location in Unicode sequence to end extracting + * (default: end of the string) + * @return {string} Extracted sub-string + */ +function substring(str, start, end) { + start = start || 0; + end = end === undefined ? Infinity : end || 0; + + if (start < 0) { + start = 0; + } + if (end < 0) { + end = 0; + } + + var length = Math.abs(end - start); + start = start < end ? start : end; + return substr(str, start, length); +} + +/** + * Get a list of Unicode code-points from a String + * + * @param {string} str Valid Unicode string + * @return {array} A list of code-points in [0..0x10FFFF] + */ +function getCodePoints(str) { + var codePoints = []; + for (var pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) { + codePoints.push(str.codePointAt(pos)); + } + return codePoints; +} + +var UnicodeUtils = { + getCodePoints: getCodePoints, + getUTF16Length: getUTF16Length, + hasSurrogateUnit: hasSurrogateUnit, + isCodeUnitInSurrogateRange: isCodeUnitInSurrogateRange, + isSurrogatePair: isSurrogatePair, + strlen: strlen, + substring: substring, + substr: substr +}; + +module.exports = UnicodeUtils; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) { + +function checkDCE() { + /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ + if ( + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' || + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function' + ) { + return; + } + if (process.env.NODE_ENV !== 'production') { + // This branch is unreachable because this function is only called + // in production, but the condition is true only in development. + // Therefore if the branch is still here, dead code elimination wasn't + // properly applied. + // Don't change the message. React DevTools relies on it. Also make sure + // this message doesn't occur elsewhere in this function, or it will cause + // a false positive. + throw new Error('^_^'); + } + try { + // Verify that the code above has been dead code eliminated (DCE'd). + __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE); + } catch (err) { + // DevTools shouldn't crash React, no matter what. + // We should still report in case we break this code. + console.error(err); + } +} + +if (process.env.NODE_ENV === 'production') { + // DCE check should happen before ReactDOM bundle executes so that + // DevTools can report bad minification during injection. + checkDCE(); + module.exports = __webpack_require__(195); +} else { + module.exports = __webpack_require__(194); +} + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SelectionState + * @format + * + */ + + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var Immutable = __webpack_require__(1); + +var Record = Immutable.Record; + + +var defaultRecord = { + anchorKey: '', + anchorOffset: 0, + focusKey: '', + focusOffset: 0, + isBackward: false, + hasFocus: false +}; + +var SelectionStateRecord = Record(defaultRecord); + +var SelectionState = function (_SelectionStateRecord) { + _inherits(SelectionState, _SelectionStateRecord); + + function SelectionState() { + _classCallCheck(this, SelectionState); + + return _possibleConstructorReturn(this, _SelectionStateRecord.apply(this, arguments)); + } + + SelectionState.prototype.serialize = function serialize() { + return 'Anchor: ' + this.getAnchorKey() + ':' + this.getAnchorOffset() + ', ' + 'Focus: ' + this.getFocusKey() + ':' + this.getFocusOffset() + ', ' + 'Is Backward: ' + String(this.getIsBackward()) + ', ' + 'Has Focus: ' + String(this.getHasFocus()); + }; + + SelectionState.prototype.getAnchorKey = function getAnchorKey() { + return this.get('anchorKey'); + }; + + SelectionState.prototype.getAnchorOffset = function getAnchorOffset() { + return this.get('anchorOffset'); + }; + + SelectionState.prototype.getFocusKey = function getFocusKey() { + return this.get('focusKey'); + }; + + SelectionState.prototype.getFocusOffset = function getFocusOffset() { + return this.get('focusOffset'); + }; + + SelectionState.prototype.getIsBackward = function getIsBackward() { + return this.get('isBackward'); + }; + + SelectionState.prototype.getHasFocus = function getHasFocus() { + return this.get('hasFocus'); + }; + + /** + * Return whether the specified range overlaps with an edge of the + * SelectionState. + */ + + + SelectionState.prototype.hasEdgeWithin = function hasEdgeWithin(blockKey, start, end) { + var anchorKey = this.getAnchorKey(); + var focusKey = this.getFocusKey(); + + if (anchorKey === focusKey && anchorKey === blockKey) { + var selectionStart = this.getStartOffset(); + var selectionEnd = this.getEndOffset(); + return start <= selectionEnd && selectionStart <= end; + } + + if (blockKey !== anchorKey && blockKey !== focusKey) { + return false; + } + + var offsetToCheck = blockKey === anchorKey ? this.getAnchorOffset() : this.getFocusOffset(); + + return start <= offsetToCheck && end >= offsetToCheck; + }; + + SelectionState.prototype.isCollapsed = function isCollapsed() { + return this.getAnchorKey() === this.getFocusKey() && this.getAnchorOffset() === this.getFocusOffset(); + }; + + SelectionState.prototype.getStartKey = function getStartKey() { + return this.getIsBackward() ? this.getFocusKey() : this.getAnchorKey(); + }; + + SelectionState.prototype.getStartOffset = function getStartOffset() { + return this.getIsBackward() ? this.getFocusOffset() : this.getAnchorOffset(); + }; + + SelectionState.prototype.getEndKey = function getEndKey() { + return this.getIsBackward() ? this.getAnchorKey() : this.getFocusKey(); + }; + + SelectionState.prototype.getEndOffset = function getEndOffset() { + return this.getIsBackward() ? this.getAnchorOffset() : this.getFocusOffset(); + }; + + SelectionState.createEmpty = function createEmpty(key) { + return new SelectionState({ + anchorKey: key, + anchorOffset: 0, + focusKey: key, + focusOffset: 0, + isBackward: false, + hasFocus: false + }); + }; + + return SelectionState; +}(SelectionStateRecord); + +module.exports = SelectionState; + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/** + * This function is used to mark string literals representing CSS class names + * so that they can be transformed statically. This allows for modularization + * and minification of CSS class names. + * + * In static_upstream, this function is actually implemented, but it should + * eventually be replaced with something more descriptive, and the transform + * that is used in the main stack should be ported for use elsewhere. + * + * @param string|object className to modularize, or an object of key/values. + * In the object case, the values are conditions that + * determine if the className keys should be included. + * @param [string ...] Variable list of classNames in the string case. + * @return string Renderable space-separated CSS className. + */ +function cx(classNames) { + if (typeof classNames == 'object') { + return Object.keys(classNames).filter(function (className) { + return classNames[className]; + }).map(replace).join(' '); + } + return Array.prototype.map.call(arguments, replace).join(' '); +} + +function replace(str) { + return str.replace(/\//g, '-'); +} + +module.exports = cx; + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule BlockMapBuilder + * @format + * + */ + + + +var Immutable = __webpack_require__(1); + +var OrderedMap = Immutable.OrderedMap; + + +var BlockMapBuilder = { + createFromArray: function createFromArray(blocks) { + return OrderedMap(blocks.map(function (block) { + return [block.getKey(), block]; + })); + } +}; + +module.exports = BlockMapBuilder; + +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule findRangesImmutable + * @format + * + */ + + + +/** + * Search through an array to find contiguous stretches of elements that + * match a specified filter function. + * + * When ranges are found, execute a specified `found` function to supply + * the values to the caller. + */ +function findRangesImmutable(haystack, areEqualFn, filterFn, foundFn) { + if (!haystack.size) { + return; + } + + var cursor = 0; + + haystack.reduce(function (value, nextValue, nextIndex) { + if (!areEqualFn(value, nextValue)) { + if (filterFn(value)) { + foundFn(cursor, nextIndex); + } + cursor = nextIndex; + } + return nextValue; + }); + + filterFn(haystack.last()) && foundFn(cursor, haystack.count()); +} + +module.exports = findRangesImmutable; + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule isEventHandled + * @format + * + */ + + + +/** + * Utility method for determining whether or not the value returned + * from a handler indicates that it was handled. + */ +function isEventHandled(value) { + return value === 'handled' || value === true; +} + +module.exports = isEventHandled; + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule removeTextWithStrategy + * @format + * + */ + + + +var DraftModifier = __webpack_require__(6); + +/** + * For a collapsed selection state, remove text based on the specified strategy. + * If the selection state is not collapsed, remove the entire selected range. + */ +function removeTextWithStrategy(editorState, strategy, direction) { + var selection = editorState.getSelection(); + var content = editorState.getCurrentContent(); + var target = selection; + if (selection.isCollapsed()) { + if (direction === 'forward') { + if (editorState.isSelectionAtEndOfContent()) { + return content; + } + } else if (editorState.isSelectionAtStartOfContent()) { + return content; + } + + target = strategy(editorState); + if (target === selection) { + return content; + } + } + return DraftModifier.removeRange(content, target, direction); +} + +module.exports = removeTextWithStrategy; + +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _Buttons = __webpack_require__(47); + +var _Buttons2 = _interopRequireDefault(_Buttons); + +var _AutoComplete = __webpack_require__(95); + +var _AutoComplete2 = _interopRequireDefault(_AutoComplete); + +var _utils = __webpack_require__(48); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var MODAL_EXIT_CLASS = 'admin-modal--exit'; +var MODAL_CLOSE_TIMEOUT = 400; +var MODAL_OPEN_TIMEOUT = 650; + +var STR = { + choose: 'Choose', + result: 'Result', + results: 'Results', + previous: 'Previous', + page: 'Page', + pages: 'Pages', + next: 'Next' +}; + +var defaultProps = { + filters: [], + page_size: 10, + page_size_param: 'page_size', + translations: {} +}; + +var propTypes = { + onSelect: _propTypes2.default.func.isRequired, + onClose: _propTypes2.default.func.isRequired, + label: _propTypes2.default.string.isRequired, + endpoint: _propTypes2.default.string.isRequired, + list_display: _propTypes2.default.array.isRequired, + filters: _propTypes2.default.array, + pk_name: _propTypes2.default.string.isRequired, + page_size: _propTypes2.default.number, + page_size_param: _propTypes2.default.string, + translations: _propTypes2.default.object +}; + +var ModelPicker = function (_React$Component) { + _inherits(ModelPicker, _React$Component); + + function ModelPicker(props) { + _classCallCheck(this, ModelPicker); + + var _this = _possibleConstructorReturn(this, (ModelPicker.__proto__ || Object.getPrototypeOf(ModelPicker)).call(this, props)); + + _this.state = { + pickerVisible: false, + models: [], + loading: true, + next: false, + previous: false, + count: 0, + url: null, + numPages: 0, + page: 0, + suggestions: [], + suggestionsCount: 0, + shouldShowSuggestions: false, + loadingSuggestions: false + }; + + _this.getDefaultUrl = _this.getDefaultUrl.bind(_this); + _this.getPk = _this.getPk.bind(_this); + _this.getModels = _this.getModels.bind(_this); + _this.select = _this.select.bind(_this); + _this.closeWithCallback = _this.closeWithCallback.bind(_this); + _this.update = _this.update.bind(_this); + _this.addFilterParams = _this.addFilterParams.bind(_this); + _this.navigate = _this.navigate.bind(_this); + _this.onClose = _this.onClose.bind(_this); + _this.handleError = _this.handleError.bind(_this); + _this.getPlaceholder = _this.getPlaceholder.bind(_this); + _this.getTable = _this.getTable.bind(_this); + _this.getHeader = _this.getHeader.bind(_this); + _this.parseValue = _this.parseValue.bind(_this); + _this.getRow = _this.getRow.bind(_this); + _this.getCount = _this.getCount.bind(_this); + _this.getCountDisplay = _this.getCountDisplay.bind(_this); + _this.getPageDisplay = _this.getPageDisplay.bind(_this); + _this.getPaginationButtons = _this.getPaginationButtons.bind(_this); + _this.navigatePrevious = _this.navigatePrevious.bind(_this); + _this.navigateNext = _this.navigateNext.bind(_this); + _this.onLoadSuggestions = _this.onLoadSuggestions.bind(_this); + _this.onValueChange = _this.onValueChange.bind(_this); + _this.onLoadStart = _this.onLoadStart.bind(_this); + return _this; + } + + _createClass(ModelPicker, [{ + key: 'componentDidMount', + value: function componentDidMount() { + var _this2 = this; + + setTimeout(function () { + _this2.navigate(_this2.getDefaultUrl()); + }, MODAL_OPEN_TIMEOUT); + + document.body.style.overflow = 'hidden'; + document.body.style.width = document.body.offsetWidth + 'px'; + } + }, { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + document.body.style.overflow = ''; + document.body.style.width = ''; + } + }, { + key: 'onClose', + value: function onClose(e) { + var onClose = this.props.onClose; + + this.closeWithCallback(function () { + onClose(e); + }); + } + }, { + key: 'onLoadSuggestions', + value: function onLoadSuggestions(suggestions) { + this.setState({ + suggestions: suggestions, + suggestionsCount: suggestions.length, + loadingSuggestions: false + }); + } + }, { + key: 'onValueChange', + value: function onValueChange(newValue) { + var shouldShowSuggestions = newValue.trim().length > 2; + + this.setState({ + shouldShowSuggestions: shouldShowSuggestions + }); + } + }, { + key: 'onLoadStart', + value: function onLoadStart() { + this.setState({ + loadingSuggestions: true + }); + } + }, { + key: 'getPaginationButtons', + value: function getPaginationButtons() { + var translations = this.props.translations; + var _state = this.state, + next = _state.next, + previous = _state.previous, + shouldShowSuggestions = _state.shouldShowSuggestions; + + + var prevLabel = (0, _utils.tr)(STR, translations, 'previous'); + var nextLabel = (0, _utils.tr)(STR, translations, 'next'); + var prevEnabled = shouldShowSuggestions ? false : !!previous; + var nextEnabled = shouldShowSuggestions ? false : !!next; + + return _react2.default.createElement( + 'span', + null, + _react2.default.createElement(_Buttons2.default, { + onClick: this.navigatePrevious, + isActive: prevEnabled, + label: prevLabel + }), + _react2.default.createElement(_Buttons2.default, { + onClick: this.navigateNext, + isActive: nextEnabled, + label: nextLabel + }) + ); + } + }, { + key: 'getPageDisplay', + value: function getPageDisplay() { + var translations = this.props.translations; + var _state2 = this.state, + numPages = _state2.numPages, + currentPage = _state2.page, + shouldShowSuggestions = _state2.shouldShowSuggestions; + + + var text = void 0; + if (shouldShowSuggestions) { + var label = (0, _utils.tr)(STR, translations, 'page'); + text = '1 / 1 ' + label; + } else { + var _label = (0, _utils.pluralize)(STR, translations, 'result', 'results', numPages); + text = currentPage + ' / ' + numPages + ' ' + _label; + } + + return _react2.default.createElement( + 'span', + { className: 'admin-modal__pagination' }, + text + ); + } + }, { + key: 'getCountDisplay', + value: function getCountDisplay() { + var translations = this.props.translations; + + var count = this.getCount(); + var label = (0, _utils.pluralize)(STR, translations, 'result', 'results', count); + + return _react2.default.createElement( + 'span', + { className: 'admin-modal__results' }, + count, + ' ', + label + ); + } + }, { + key: 'getRow', + value: function getRow(item) { + var _this3 = this; + + var listDisplay = this.props.list_display; + + + return (// eslint-disable-next-line + _react2.default.createElement( + 'tr', + { + key: this.getPk(item), + className: 'chooser__item', + onClick: function onClick() { + return _this3.select(_this3.getPk(item)); + } + }, + listDisplay.map(function (field) { + var value = item[field.name]; + + return _react2.default.createElement( + 'td', + { key: field.name, className: 'chooser__cell' }, + _this3.parseValue(value, field.name) + ); + }) + ) + ); + } + }, { + key: 'getCount', + value: function getCount() { + var _state3 = this.state, + count = _state3.count, + shouldShowSuggestions = _state3.shouldShowSuggestions, + suggestionsCount = _state3.suggestionsCount; + + + return shouldShowSuggestions ? suggestionsCount : count; + } + + // eslint-disable-next-line + + }, { + key: 'getHeader', + value: function getHeader(field) { + return _react2.default.createElement( + 'td', + { key: field.name }, + field.label + ); + } + }, { + key: 'getTable', + value: function getTable() { + var listDisplay = this.props.list_display; + + var models = this.getModels(); + + return _react2.default.createElement( + 'table', + { className: 'chooser-table' }, + _react2.default.createElement( + 'thead', + null, + _react2.default.createElement( + 'tr', + null, + listDisplay.map(this.getHeader) + ) + ), + _react2.default.createElement( + 'tbody', + null, + models.length ? models.map(this.getRow) : this.getPlaceholder() + ) + ); + } + }, { + key: 'getPlaceholder', + value: function getPlaceholder() { + var listDisplay = this.props.list_display; + var loading = this.state.loading; + + + return _react2.default.createElement( + 'tr', + { className: 'chooser__item' }, + _react2.default.createElement( + 'td', + { colSpan: listDisplay.length, className: 'chooser__cell chooser__cell--disabled' }, + loading ? 'Loading' : 'Sorry, no results' + ) + ); + } + }, { + key: 'getModels', + value: function getModels() { + var _state4 = this.state, + shouldShowSuggestions = _state4.shouldShowSuggestions, + suggestions = _state4.suggestions, + models = _state4.models; + + + return shouldShowSuggestions ? suggestions : models; + } + }, { + key: 'getPk', + value: function getPk(item) { + var pk_name = this.props.pk_name; + + + return item ? item[pk_name] : null; + } + }, { + key: 'getDefaultUrl', + value: function getDefaultUrl() { + var _props = this.props, + endpoint = _props.endpoint, + pageSize = _props.page_size, + pageSizeParam = _props.page_size_param; + + return endpoint + '/?' + pageSizeParam + '=' + pageSize; + } + }, { + key: 'select', + value: function select(pk) { + var _this4 = this; + + var onSelect = this.props.onSelect; + var url = this.state.url; + + var models = this.getModels(); + var item = models.find(function (m) { + return _this4.getPk(m) === pk; + }); + + this.closeWithCallback(function () { + onSelect(_this4.getPk(item), item, url); + }); + } + }, { + key: 'navigateNext', + value: function navigateNext() { + var _state5 = this.state, + shouldShowSuggestions = _state5.shouldShowSuggestions, + page = _state5.page; + + + if (shouldShowSuggestions) { + return; + } + + var url = this.getDefaultUrl() + '&page=' + (page + 1); + this.navigate(url); + } + }, { + key: 'navigatePrevious', + value: function navigatePrevious() { + var _state6 = this.state, + shouldShowSuggestions = _state6.shouldShowSuggestions, + page = _state6.page; + + + if (shouldShowSuggestions) { + return; + } + + var url = this.getDefaultUrl() + '&page=' + (page - 1); + this.navigate(url); + } + + // eslint-disable-next-line + + }, { + key: 'parseValue', + value: function parseValue(value, fieldName) { + var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); + + if (type === 'string') { + return value; + } + + if (type === 'number') { + return value; + } + + if (type === 'object') { + // Django internals + if (fieldName === 'content_type') { + return value.model; + } + } + + if (type === 'boolean') { + return value ? 'True' : 'False'; + } + + return ''; + } + }, { + key: 'handleError', + value: function handleError() { + this.setState({ + loading: false + }); + } + }, { + key: 'navigate', + value: function navigate(url) { + var _this5 = this; + + var urlWithFilters = this.addFilterParams(url); + this.setState({ + loading: true, + url: url + }, function () { + // TODO There is no reason for this code to be in the setState callback. + // TODO This is not producing errors when status code is not 200, + // so the error handling likely does not work. + // TODO Use fetch API wrapper. + fetch(urlWithFilters, { + credentials: 'same-origin' + }).then(function (res) { + return res.json(); + }).then(_this5.update, _this5.handleError); + }); + } + }, { + key: 'addFilterParams', + value: function addFilterParams(url) { + var filters = this.props.filters; + + var localUrl = url; + + if (filters) { + // TODO Redo with map and join. + filters.forEach(function (filter) { + localUrl += '&' + filter.field + '=' + filter.value; + }); + } + + return localUrl; + } + }, { + key: 'update', + value: function update(json) { + var _this6 = this; + + var pageSize = this.props.page_size; + + // If the API does not return the total number of page, + // try to calculate it from the number of result and the page size. + + var numPage = 0; + if (json.num_pages) { + numPage = json.num_pages; + } else if (json.count) { + numPage = Math.ceil(json.count / pageSize); + } + + this.setState({ + numPages: numPage, + page: json.page, + models: json.results, + count: json.count, + next: json.next, + previous: json.previous, + loading: false + }, function () { + _this6.contentRef.scrollTop = 0; + }); + } + }, { + key: 'closeWithCallback', + value: function closeWithCallback(callback) { + this.elRef.classList.add(MODAL_EXIT_CLASS); + setTimeout(callback, MODAL_CLOSE_TIMEOUT); + } + }, { + key: 'render', + value: function render() { + var _this7 = this; + + var _props2 = this.props, + endpoint = _props2.endpoint, + label = _props2.label, + translations = _props2.translations; + + var chooseHeading = (0, _utils.tr)(STR, translations, 'choose'); + + return _react2.default.createElement( + 'div', + { className: 'modal admin-modal', ref: function ref(el) { + _this7.elRef = el; + } }, + _react2.default.createElement( + 'div', + { className: 'admin-modal__dialog' }, + _react2.default.createElement( + 'div', + { className: 'admin-modal__header' }, + _react2.default.createElement( + 'h2', + null, + chooseHeading, + ' ', + label + ), + _react2.default.createElement(_Buttons.CloseButton, { onClick: this.onClose }) + ), + _react2.default.createElement( + 'div', + { className: 'admin-modal__actions' }, + _react2.default.createElement( + 'div', + { className: 'admin-modal__action' }, + _react2.default.createElement(_AutoComplete2.default, { + onChange: this.onValueChange, + onLoadSuggestions: this.onLoadSuggestions, + onLoadStart: this.onLoadStart, + endpoint: endpoint, + filter: this.addFilterParams('') + }) + ), + _react2.default.createElement( + 'div', + { className: 'admin-modal__action' }, + this.getCountDisplay(), + this.getPageDisplay(), + this.getPaginationButtons() + ) + ), + _react2.default.createElement( + 'div', + { className: 'admin-modal__content', ref: function ref(content) { + _this7.contentRef = content; + } }, + this.getTable() + ) + ) + ); + } + }]); + + return ModelPicker; +}(_react2.default.Component); + +ModelPicker.defaultProps = defaultProps; +ModelPicker.propTypes = propTypes; + +exports.default = ModelPicker; + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) { + +var _assign = __webpack_require__(5); + +var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEntity + * @format + * + */ + +var DraftEntityInstance = __webpack_require__(53); +var Immutable = __webpack_require__(1); + +var invariant = __webpack_require__(2); + +var Map = Immutable.Map; + + +var instances = Map(); +var instanceKey = 0; + +/** + * Temporary utility for generating the warnings + */ +function logWarning(oldMethodCall, newMethodCall) { + console.warn('WARNING: ' + oldMethodCall + ' will be deprecated soon!\nPlease use "' + newMethodCall + '" instead.'); +} + +/** + * A "document entity" is an object containing metadata associated with a + * piece of text in a ContentBlock. + * + * For example, a `link` entity might include a `uri` property. When a + * ContentBlock is rendered in the browser, text that refers to that link + * entity may be rendered as an anchor, with the `uri` as the href value. + * + * In a ContentBlock, every position in the text may correspond to zero + * or one entities. This correspondence is tracked using a key string, + * generated via DraftEntity.create() and used to obtain entity metadata + * via DraftEntity.get(). + */ +var DraftEntity = { + /** + * WARNING: This method will be deprecated soon! + * Please use 'contentState.getLastCreatedEntityKey' instead. + * --- + * Get the random key string from whatever entity was last created. + * We need this to support the new API, as part of transitioning to put Entity + * storage in contentState. + */ + getLastCreatedEntityKey: function getLastCreatedEntityKey() { + logWarning('DraftEntity.getLastCreatedEntityKey', 'contentState.getLastCreatedEntityKey'); + return DraftEntity.__getLastCreatedEntityKey(); + }, + + /** + * WARNING: This method will be deprecated soon! + * Please use 'contentState.createEntity' instead. + * --- + * Create a DraftEntityInstance and store it for later retrieval. + * + * A random key string will be generated and returned. This key may + * be used to track the entity's usage in a ContentBlock, and for + * retrieving data about the entity at render time. + */ + create: function create(type, mutability, data) { + logWarning('DraftEntity.create', 'contentState.createEntity'); + return DraftEntity.__create(type, mutability, data); + }, + + /** + * WARNING: This method will be deprecated soon! + * Please use 'contentState.addEntity' instead. + * --- + * Add an existing DraftEntityInstance to the DraftEntity map. This is + * useful when restoring instances from the server. + */ + add: function add(instance) { + logWarning('DraftEntity.add', 'contentState.addEntity'); + return DraftEntity.__add(instance); + }, + + /** + * WARNING: This method will be deprecated soon! + * Please use 'contentState.getEntity' instead. + * --- + * Retrieve the entity corresponding to the supplied key string. + */ + get: function get(key) { + logWarning('DraftEntity.get', 'contentState.getEntity'); + return DraftEntity.__get(key); + }, + + /** + * WARNING: This method will be deprecated soon! + * Please use 'contentState.mergeEntityData' instead. + * --- + * Entity instances are immutable. If you need to update the data for an + * instance, this method will merge your data updates and return a new + * instance. + */ + mergeData: function mergeData(key, toMerge) { + logWarning('DraftEntity.mergeData', 'contentState.mergeEntityData'); + return DraftEntity.__mergeData(key, toMerge); + }, + + /** + * WARNING: This method will be deprecated soon! + * Please use 'contentState.replaceEntityData' instead. + * --- + * Completely replace the data for a given instance. + */ + replaceData: function replaceData(key, newData) { + logWarning('DraftEntity.replaceData', 'contentState.replaceEntityData'); + return DraftEntity.__replaceData(key, newData); + }, + + // ***********************************WARNING****************************** + // --- the above public API will be deprecated in the next version of Draft! + // The methods below this line are private - don't call them directly. + + /** + * Get the random key string from whatever entity was last created. + * We need this to support the new API, as part of transitioning to put Entity + * storage in contentState. + */ + __getLastCreatedEntityKey: function __getLastCreatedEntityKey() { + return '' + instanceKey; + }, + + /** + * Create a DraftEntityInstance and store it for later retrieval. + * + * A random key string will be generated and returned. This key may + * be used to track the entity's usage in a ContentBlock, and for + * retrieving data about the entity at render time. + */ + __create: function __create(type, mutability, data) { + return DraftEntity.__add(new DraftEntityInstance({ type: type, mutability: mutability, data: data || {} })); + }, + + /** + * Add an existing DraftEntityInstance to the DraftEntity map. This is + * useful when restoring instances from the server. + */ + __add: function __add(instance) { + var key = '' + ++instanceKey; + instances = instances.set(key, instance); + return key; + }, + + /** + * Retrieve the entity corresponding to the supplied key string. + */ + __get: function __get(key) { + var instance = instances.get(key); + !!!instance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unknown DraftEntity key: %s.', key) : invariant(false) : void 0; + return instance; + }, + + /** + * Entity instances are immutable. If you need to update the data for an + * instance, this method will merge your data updates and return a new + * instance. + */ + __mergeData: function __mergeData(key, toMerge) { + var instance = DraftEntity.__get(key); + var newData = _extends({}, instance.getData(), toMerge); + var newInstance = instance.set('data', newData); + instances = instances.set(key, newInstance); + return newInstance; + }, + + /** + * Completely replace the data for a given instance. + */ + __replaceData: function __replaceData(key, newData) { + var instance = DraftEntity.__get(key); + var newInstance = instance.set('data', newData); + instances = instances.set(key, newInstance); + return newInstance; + } +}; + +module.exports = DraftEntity; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftOffsetKey + * @format + * + */ + + + +var KEY_DELIMITER = '-'; + +var DraftOffsetKey = { + encode: function encode(blockKey, decoratorKey, leafKey) { + return blockKey + KEY_DELIMITER + decoratorKey + KEY_DELIMITER + leafKey; + }, + + decode: function decode(offsetKey) { + var _offsetKey$split = offsetKey.split(KEY_DELIMITER), + blockKey = _offsetKey$split[0], + decoratorKey = _offsetKey$split[1], + leafKey = _offsetKey$split[2]; + + return { + blockKey: blockKey, + decoratorKey: parseInt(decoratorKey, 10), + leafKey: parseInt(leafKey, 10) + }; + } +}; + +module.exports = DraftOffsetKey; + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getContentStateFragment + * @format + * + */ + + + +var randomizeBlockMapKeys = __webpack_require__(70); +var removeEntitiesAtEdges = __webpack_require__(71); + +var getContentStateFragment = function getContentStateFragment(contentState, selectionState) { + var startKey = selectionState.getStartKey(); + var startOffset = selectionState.getStartOffset(); + var endKey = selectionState.getEndKey(); + var endOffset = selectionState.getEndOffset(); + + // Edge entities should be stripped to ensure that we don't preserve + // invalid partial entities when the fragment is reused. We do, however, + // preserve entities that are entirely within the selection range. + var contentWithoutEdgeEntities = removeEntitiesAtEdges(contentState, selectionState); + + var blockMap = contentWithoutEdgeEntities.getBlockMap(); + var blockKeys = blockMap.keySeq(); + var startIndex = blockKeys.indexOf(startKey); + var endIndex = blockKeys.indexOf(endKey) + 1; + + return randomizeBlockMapKeys(blockMap.slice(startIndex, endIndex).map(function (block, blockKey) { + var text = block.getText(); + var chars = block.getCharacterList(); + + if (startKey === endKey) { + return block.merge({ + text: text.slice(startOffset, endOffset), + characterList: chars.slice(startOffset, endOffset) + }); + } + + if (blockKey === startKey) { + return block.merge({ + text: text.slice(startOffset), + characterList: chars.slice(startOffset) + }); + } + + if (blockKey === endKey) { + return block.merge({ + text: text.slice(0, endOffset), + characterList: chars.slice(0, endOffset) + }); + } + + return block; + })); +}; + +module.exports = getContentStateFragment; + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _Buttons = __webpack_require__(47); + +var _ModelPicker = __webpack_require__(24); + +var _ModelPicker2 = _interopRequireDefault(_ModelPicker); + +var _utils = __webpack_require__(48); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var STR = { + choose: 'Choose', + choose_again: 'Choose another', + clear: 'Clear choice' +}; + +var defaultProps = { + display: 'title', + filters: [], + translations: {}, + pk_name: 'uuid', + page_size: 10, + page_size_param: 'page_size' +}; + +var propTypes = { + initialValue: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.object]).isRequired, + updateInputValue: _propTypes2.default.func.isRequired, + initial_display_value: _propTypes2.default.string.isRequired, + required: _propTypes2.default.bool.isRequired, + display: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.array]).isRequired, + pk_name: _propTypes2.default.string, + translations: _propTypes2.default.object, + label: _propTypes2.default.string.isRequired, + list_display: _propTypes2.default.array.isRequired, + filters: _propTypes2.default.array, + endpoint: _propTypes2.default.string.isRequired, + page_size: _propTypes2.default.number, + page_size_param: _propTypes2.default.string +}; + +var BaseChooser = function (_React$Component) { + _inherits(BaseChooser, _React$Component); + + function BaseChooser(props) { + _classCallCheck(this, BaseChooser); + + var _this = _possibleConstructorReturn(this, (BaseChooser.__proto__ || Object.getPrototypeOf(BaseChooser)).call(this, props)); + + var _this$props = _this.props, + display = _this$props.display, + initialValue = _this$props.initialValue, + initialDisplayValue = _this$props.initial_display_value; + + // If `initialValue` is an object (i.e. the item), use it directly, + // otherwise create a new object and use the `initialValue` for the ID. + + var hasInitialObject = initialValue !== null && (typeof initialValue === 'undefined' ? 'undefined' : _typeof(initialValue)) === 'object'; + var selectedItem = hasInitialObject ? initialValue : {}; + var selectedId = hasInitialObject ? _this.getItemPk(selectedItem) : initialValue; + + // Ensure the item has the required key for `display`. + var displayKey = Array.isArray(display) ? display[0] : display; + if (!(displayKey in selectedItem)) { + selectedItem[displayKey] = initialDisplayValue; + } + + _this.state = { + pickerVisible: false, + selectedId: selectedId, + selectedItem: selectedItem, + initialUrl: null + }; + + _this.showPicker = _this.showPicker.bind(_this); + _this.onClose = _this.onClose.bind(_this); + _this.onSelect = _this.onSelect.bind(_this); + _this.getItemPk = _this.getItemPk.bind(_this); + _this.getItemPreview = _this.getItemPreview.bind(_this); + _this.isOptional = _this.isOptional.bind(_this); + _this.getChooseButtons = _this.getChooseButtons.bind(_this); + _this.clearPicker = _this.clearPicker.bind(_this); + return _this; + } + + _createClass(BaseChooser, [{ + key: 'onClose', + value: function onClose() { + this.setState({ + pickerVisible: false + }); + } + }, { + key: 'onSelect', + value: function onSelect(id, item, url) { + var _this2 = this; + + this.setState({ + selectedId: id, + selectedItem: item, + pickerVisible: false, + initialUrl: url + }, function () { + _this2.props.updateInputValue(item); + }); + } + }, { + key: 'getItemPk', + value: function getItemPk(item) { + var pkName = this.props.pk_name; + + + return item ? item[pkName] : null; + } + }, { + key: 'getItemPreview', + value: function getItemPreview() { + var display = this.props.display; + var selectedItem = this.state.selectedItem; + + + if (!selectedItem) { + return ''; + } + + // Return first non-empty field if `display` is an Array. + if (Array.isArray(display)) { + var i = void 0; + for (i = 0; i < display.length; i += 1) { + var fieldName = display[i]; + if (fieldName in selectedItem && selectedItem[fieldName]) { + return selectedItem[fieldName]; + } + } + } + + // Return the `display` field if available. + if (display in selectedItem && selectedItem[display]) { + return selectedItem[display]; + } + + // Return the object PK as default. + return this.getItemPk(selectedItem); + } + }, { + key: 'getChooseButtons', + value: function getChooseButtons() { + var translations = this.props.translations; + var selectedId = this.state.selectedId; + + + if (!selectedId) { + return _react2.default.createElement(_Buttons.SecondaryButton, { + onClick: this.showPicker, + label: (0, _utils.tr)(STR, translations, 'choose') + }); + } + + return _react2.default.createElement( + 'span', + null, + _react2.default.createElement(_Buttons.SecondaryButton, { + onClick: this.showPicker, + label: (0, _utils.tr)(STR, translations, 'choose_again') + }), + this.isOptional() ? _react2.default.createElement(_Buttons.SecondaryButton, { + onClick: this.clearPicker, + label: (0, _utils.tr)(STR, translations, 'clear') + }) : null + ); + } + }, { + key: 'isOptional', + value: function isOptional() { + var required = this.props.required; + + return !required; + } + }, { + key: 'showPicker', + value: function showPicker() { + this.setState({ + pickerVisible: true + }); + } + }, { + key: 'clearPicker', + value: function clearPicker(e) { + var _this3 = this; + + e.preventDefault(); + + this.setState({ + selectedId: null, + selectedItem: null, + pickerVisible: false, + initialUrl: null + }, function () { + _this3.props.updateInputValue(null); + }); + } + }, { + key: 'render', + value: function render() { + var _state = this.state, + pickerVisible = _state.pickerVisible, + initialUrl = _state.initialUrl; + var _props = this.props, + listDisplay = _props.list_display, + label = _props.label, + endpoint = _props.endpoint, + filters = _props.filters, + pkName = _props.pk_name, + pageSize = _props.page_size, + pageSizeParam = _props.page_size_param, + translations = _props.translations; + + + return _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + 'span', + { className: 'model-chooser__label' }, + this.getItemPreview() + ), + this.getChooseButtons() + ), + pickerVisible ? _react2.default.createElement(_ModelPicker2.default, { + url: initialUrl, + onClose: this.onClose, + onSelect: this.onSelect, + label: label, + endpoint: endpoint, + filters: filters, + list_display: listDisplay, + pk_name: pkName, + page_size: pageSize, + page_size_param: pageSizeParam, + translations: translations + }) : null + ); + } + }]); + + return BaseChooser; +}(_react2.default.Component); + +BaseChooser.defaultProps = defaultProps; +BaseChooser.propTypes = propTypes; + +exports.default = BaseChooser; + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ContentState + * @format + * + */ + + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var BlockMapBuilder = __webpack_require__(20); +var CharacterMetadata = __webpack_require__(7); +var ContentBlock = __webpack_require__(15); +var ContentBlockNode = __webpack_require__(9); +var DraftEntity = __webpack_require__(25); +var DraftFeatureFlags = __webpack_require__(14); +var Immutable = __webpack_require__(1); +var SelectionState = __webpack_require__(18); + +var generateRandomKey = __webpack_require__(13); +var sanitizeDraftText = __webpack_require__(35); + +var List = Immutable.List, + Record = Immutable.Record, + Repeat = Immutable.Repeat; + + +var experimentalTreeDataSupport = DraftFeatureFlags.draft_tree_data_support; + +var defaultRecord = { + entityMap: null, + blockMap: null, + selectionBefore: null, + selectionAfter: null +}; + +var ContentBlockNodeRecord = experimentalTreeDataSupport ? ContentBlockNode : ContentBlock; + +var ContentStateRecord = Record(defaultRecord); + +var ContentState = function (_ContentStateRecord) { + _inherits(ContentState, _ContentStateRecord); + + function ContentState() { + _classCallCheck(this, ContentState); + + return _possibleConstructorReturn(this, _ContentStateRecord.apply(this, arguments)); + } + + ContentState.prototype.getEntityMap = function getEntityMap() { + // TODO: update this when we fully remove DraftEntity + return DraftEntity; + }; + + ContentState.prototype.getBlockMap = function getBlockMap() { + return this.get('blockMap'); + }; + + ContentState.prototype.getSelectionBefore = function getSelectionBefore() { + return this.get('selectionBefore'); + }; + + ContentState.prototype.getSelectionAfter = function getSelectionAfter() { + return this.get('selectionAfter'); + }; + + ContentState.prototype.getBlockForKey = function getBlockForKey(key) { + var block = this.getBlockMap().get(key); + return block; + }; + + ContentState.prototype.getKeyBefore = function getKeyBefore(key) { + return this.getBlockMap().reverse().keySeq().skipUntil(function (v) { + return v === key; + }).skip(1).first(); + }; + + ContentState.prototype.getKeyAfter = function getKeyAfter(key) { + return this.getBlockMap().keySeq().skipUntil(function (v) { + return v === key; + }).skip(1).first(); + }; + + ContentState.prototype.getBlockAfter = function getBlockAfter(key) { + return this.getBlockMap().skipUntil(function (_, k) { + return k === key; + }).skip(1).first(); + }; + + ContentState.prototype.getBlockBefore = function getBlockBefore(key) { + return this.getBlockMap().reverse().skipUntil(function (_, k) { + return k === key; + }).skip(1).first(); + }; + + ContentState.prototype.getBlocksAsArray = function getBlocksAsArray() { + return this.getBlockMap().toArray(); + }; + + ContentState.prototype.getFirstBlock = function getFirstBlock() { + return this.getBlockMap().first(); + }; + + ContentState.prototype.getLastBlock = function getLastBlock() { + return this.getBlockMap().last(); + }; + + ContentState.prototype.getPlainText = function getPlainText(delimiter) { + return this.getBlockMap().map(function (block) { + return block ? block.getText() : ''; + }).join(delimiter || '\n'); + }; + + ContentState.prototype.getLastCreatedEntityKey = function getLastCreatedEntityKey() { + // TODO: update this when we fully remove DraftEntity + return DraftEntity.__getLastCreatedEntityKey(); + }; + + ContentState.prototype.hasText = function hasText() { + var blockMap = this.getBlockMap(); + return blockMap.size > 1 || blockMap.first().getLength() > 0; + }; + + ContentState.prototype.createEntity = function createEntity(type, mutability, data) { + // TODO: update this when we fully remove DraftEntity + DraftEntity.__create(type, mutability, data); + return this; + }; + + ContentState.prototype.mergeEntityData = function mergeEntityData(key, toMerge) { + // TODO: update this when we fully remove DraftEntity + DraftEntity.__mergeData(key, toMerge); + return this; + }; + + ContentState.prototype.replaceEntityData = function replaceEntityData(key, newData) { + // TODO: update this when we fully remove DraftEntity + DraftEntity.__replaceData(key, newData); + return this; + }; + + ContentState.prototype.addEntity = function addEntity(instance) { + // TODO: update this when we fully remove DraftEntity + DraftEntity.__add(instance); + return this; + }; + + ContentState.prototype.getEntity = function getEntity(key) { + // TODO: update this when we fully remove DraftEntity + return DraftEntity.__get(key); + }; + + ContentState.createFromBlockArray = function createFromBlockArray( + // TODO: update flow type when we completely deprecate the old entity API + blocks, entityMap) { + // TODO: remove this when we completely deprecate the old entity API + var theBlocks = Array.isArray(blocks) ? blocks : blocks.contentBlocks; + var blockMap = BlockMapBuilder.createFromArray(theBlocks); + var selectionState = blockMap.isEmpty() ? new SelectionState() : SelectionState.createEmpty(blockMap.first().getKey()); + return new ContentState({ + blockMap: blockMap, + entityMap: entityMap || DraftEntity, + selectionBefore: selectionState, + selectionAfter: selectionState + }); + }; + + ContentState.createFromText = function createFromText(text) { + var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : /\r\n?|\n/g; + + var strings = text.split(delimiter); + var blocks = strings.map(function (block) { + block = sanitizeDraftText(block); + return new ContentBlockNodeRecord({ + key: generateRandomKey(), + text: block, + type: 'unstyled', + characterList: List(Repeat(CharacterMetadata.EMPTY, block.length)) + }); + }); + return ContentState.createFromBlockArray(blocks); + }; + + return ContentState; +}(ContentStateRecord); + +module.exports = ContentState; + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DefaultDraftBlockRenderMap + * @format + * + */ + + + +var _require = __webpack_require__(1), + Map = _require.Map; + +var React = __webpack_require__(4); + +var cx = __webpack_require__(19); + +var UL_WRAP = React.createElement('ul', { className: cx('public/DraftStyleDefault/ul') }); +var OL_WRAP = React.createElement('ol', { className: cx('public/DraftStyleDefault/ol') }); +var PRE_WRAP = React.createElement('pre', { className: cx('public/DraftStyleDefault/pre') }); + +var DefaultDraftBlockRenderMap = Map({ + 'header-one': { + element: 'h1' + }, + 'header-two': { + element: 'h2' + }, + 'header-three': { + element: 'h3' + }, + 'header-four': { + element: 'h4' + }, + 'header-five': { + element: 'h5' + }, + 'header-six': { + element: 'h6' + }, + 'unordered-list-item': { + element: 'li', + wrapper: UL_WRAP + }, + 'ordered-list-item': { + element: 'li', + wrapper: OL_WRAP + }, + blockquote: { + element: 'blockquote' + }, + atomic: { + element: 'figure' + }, + 'code-block': { + element: 'pre', + wrapper: PRE_WRAP + }, + unstyled: { + element: 'div', + aliasedElements: ['p'] + } +}); + +module.exports = DefaultDraftBlockRenderMap; + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule KeyBindingUtil + * @format + * + */ + + + +var UserAgent = __webpack_require__(12); + +var isOSX = UserAgent.isPlatform('Mac OS X'); + +var KeyBindingUtil = { + /** + * Check whether the ctrlKey modifier is *not* being used in conjunction with + * the altKey modifier. If they are combined, the result is an `altGraph` + * key modifier, which should not be handled by this set of key bindings. + */ + isCtrlKeyCommand: function isCtrlKeyCommand(e) { + return !!e.ctrlKey && !e.altKey; + }, + + isOptionKeyCommand: function isOptionKeyCommand(e) { + return isOSX && e.altKey; + }, + + hasCommandModifier: function hasCommandModifier(e) { + return isOSX ? !!e.metaKey && !e.altKey : KeyBindingUtil.isCtrlKeyCommand(e); + } +}; + +module.exports = KeyBindingUtil; + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule findAncestorOffsetKey + * @format + * + */ + + + +var getSelectionOffsetKeyForNode = __webpack_require__(64); + +/** + * Get the key from the node's nearest offset-aware ancestor. + */ +function findAncestorOffsetKey(node) { + var searchNode = node; + while (searchNode && searchNode !== document.documentElement) { + var key = getSelectionOffsetKeyForNode(searchNode); + if (key != null) { + return key; + } + searchNode = searchNode.parentNode; + } + return null; +} + +module.exports = findAncestorOffsetKey; + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getEntityKeyForSelection + * @format + * + */ + + + +/** + * Return the entity key that should be used when inserting text for the + * specified target selection, only if the entity is `MUTABLE`. `IMMUTABLE` + * and `SEGMENTED` entities should not be used for insertion behavior. + */ +function getEntityKeyForSelection(contentState, targetSelection) { + var entityKey; + + if (targetSelection.isCollapsed()) { + var key = targetSelection.getAnchorKey(); + var offset = targetSelection.getAnchorOffset(); + if (offset > 0) { + entityKey = contentState.getBlockForKey(key).getEntityAt(offset - 1); + if (entityKey !== contentState.getBlockForKey(key).getEntityAt(offset)) { + return null; + } + return filterKey(contentState.getEntityMap(), entityKey); + } + return null; + } + + var startKey = targetSelection.getStartKey(); + var startOffset = targetSelection.getStartOffset(); + var startBlock = contentState.getBlockForKey(startKey); + + entityKey = startOffset === startBlock.getLength() ? null : startBlock.getEntityAt(startOffset); + + return filterKey(contentState.getEntityMap(), entityKey); +} + +/** + * Determine whether an entity key corresponds to a `MUTABLE` entity. If so, + * return it. If not, return null. + */ +function filterKey(entityMap, entityKey) { + if (entityKey) { + var entity = entityMap.__get(entityKey); + return entity.getMutability() === 'MUTABLE' ? entityKey : null; + } + return null; +} + +module.exports = getEntityKeyForSelection; + +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule moveSelectionBackward + * @format + * + */ + + + +/** + * Given a collapsed selection, move the focus `maxDistance` backward within + * the selected block. If the selection will go beyond the start of the block, + * move focus to the end of the previous block, but no further. + * + * This function is not Unicode-aware, so surrogate pairs will be treated + * as having length 2. + */ +function moveSelectionBackward(editorState, maxDistance) { + var selection = editorState.getSelection(); + var content = editorState.getCurrentContent(); + var key = selection.getStartKey(); + var offset = selection.getStartOffset(); + + var focusKey = key; + var focusOffset = 0; + + if (maxDistance > offset) { + var keyBefore = content.getKeyBefore(key); + if (keyBefore == null) { + focusKey = key; + } else { + focusKey = keyBefore; + var blockBefore = content.getBlockForKey(keyBefore); + focusOffset = blockBefore.getText().length; + } + } else { + focusOffset = offset - maxDistance; + } + + return selection.merge({ + focusKey: focusKey, + focusOffset: focusOffset, + isBackward: true + }); +} + +module.exports = moveSelectionBackward; + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule sanitizeDraftText + * @format + * + */ + + + +var REGEX_BLOCK_DELIMITER = new RegExp('\r', 'g'); + +function sanitizeDraftText(input) { + return input.replace(REGEX_BLOCK_DELIMITER, ''); +} + +module.exports = sanitizeDraftText; + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +module.exports = { + BACKSPACE: 8, + TAB: 9, + RETURN: 13, + ALT: 18, + ESC: 27, + SPACE: 32, + PAGE_UP: 33, + PAGE_DOWN: 34, + END: 35, + HOME: 36, + LEFT: 37, + UP: 38, + RIGHT: 39, + DOWN: 40, + DELETE: 46, + COMMA: 188, + PERIOD: 190, + A: 65, + Z: 90, + ZERO: 48, + NUMPAD_0: 96, + NUMPAD_9: 105 +}; + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +var getStyleProperty = __webpack_require__(174); + +/** + * @param {DOMNode} element [description] + * @param {string} name Overflow style property name. + * @return {boolean} True if the supplied ndoe is scrollable. + */ +function _isNodeScrollable(element, name) { + var overflow = Style.get(element, name); + return overflow === 'auto' || overflow === 'scroll'; +} + +/** + * Utilities for querying and mutating style properties. + */ +var Style = { + /** + * Gets the style property for the supplied node. This will return either the + * computed style, if available, or the declared style. + * + * @param {DOMNode} node + * @param {string} name Style property name. + * @return {?string} Style property value. + */ + get: getStyleProperty, + + /** + * Determines the nearest ancestor of a node that is scrollable. + * + * NOTE: This can be expensive if used repeatedly or on a node nested deeply. + * + * @param {?DOMNode} node Node from which to start searching. + * @return {?DOMWindow|DOMElement} Scroll parent of the supplied node. + */ + getScrollParent: function getScrollParent(node) { + if (!node) { + return null; + } + var ownerDocument = node.ownerDocument; + while (node && node !== ownerDocument.body) { + if (_isNodeScrollable(node, 'overflow') || _isNodeScrollable(node, 'overflowY') || _isNodeScrollable(node, 'overflowX')) { + return node; + } + node = node.parentNode; + } + return ownerDocument.defaultView || ownerDocument.parentWindow; + } + +}; + +module.exports = Style; + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + * + */ + +/** + * Constants to represent text directionality + * + * Also defines a *global* direciton, to be used in bidi algorithms as a + * default fallback direciton, when no better direction is found or provided. + * + * NOTE: Use `setGlobalDir()`, or update `initGlobalDir()`, to set the initial + * global direction value based on the application. + * + * Part of the implementation of Unicode Bidirectional Algorithm (UBA) + * Unicode Standard Annex #9 (UAX9) + * http://www.unicode.org/reports/tr9/ + */ + + + +var invariant = __webpack_require__(2); + +var NEUTRAL = 'NEUTRAL'; // No strong direction +var LTR = 'LTR'; // Left-to-Right direction +var RTL = 'RTL'; // Right-to-Left direction + +var globalDir = null; + +// == Helpers == + +/** + * Check if a directionality value is a Strong one + */ +function isStrong(dir) { + return dir === LTR || dir === RTL; +} + +/** + * Get string value to be used for `dir` HTML attribute or `direction` CSS + * property. + */ +function getHTMLDir(dir) { + !isStrong(dir) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dir` must be a strong direction to be converted to HTML Direction') : invariant(false) : void 0; + return dir === LTR ? 'ltr' : 'rtl'; +} + +/** + * Get string value to be used for `dir` HTML attribute or `direction` CSS + * property, but returns null if `dir` has same value as `otherDir`. + * `null`. + */ +function getHTMLDirIfDifferent(dir, otherDir) { + !isStrong(dir) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dir` must be a strong direction to be converted to HTML Direction') : invariant(false) : void 0; + !isStrong(otherDir) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`otherDir` must be a strong direction to be converted to HTML Direction') : invariant(false) : void 0; + return dir === otherDir ? null : getHTMLDir(dir); +} + +// == Global Direction == + +/** + * Set the global direction. + */ +function setGlobalDir(dir) { + globalDir = dir; +} + +/** + * Initialize the global direction + */ +function initGlobalDir() { + setGlobalDir(LTR); +} + +/** + * Get the global direction + */ +function getGlobalDir() { + if (!globalDir) { + this.initGlobalDir(); + } + !globalDir ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Global direction not set.') : invariant(false) : void 0; + return globalDir; +} + +var UnicodeBidiDirection = { + // Values + NEUTRAL: NEUTRAL, + LTR: LTR, + RTL: RTL, + // Helpers + isStrong: isStrong, + getHTMLDir: getHTMLDir, + getHTMLDirIfDifferent: getHTMLDirIfDifferent, + // Global Direction + setGlobalDir: setGlobalDir, + initGlobalDir: initGlobalDir, + getGlobalDir: getGlobalDir +}; + +module.exports = UnicodeBidiDirection; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + */ + +var isTextNode = __webpack_require__(179); + +/*eslint-disable no-bitwise */ + +/** + * Checks if a given DOM node contains or is another DOM node. + */ +function containsNode(outerNode, innerNode) { + if (!outerNode || !innerNode) { + return false; + } else if (outerNode === innerNode) { + return true; + } else if (isTextNode(outerNode)) { + return false; + } else if (isTextNode(innerNode)) { + return containsNode(outerNode, innerNode.parentNode); + } else if ('contains' in outerNode) { + return outerNode.contains(innerNode); + } else if (outerNode.compareDocumentPosition) { + return !!(outerNode.compareDocumentPosition(innerNode) & 16); + } else { + return false; + } +} + +module.exports = containsNode; + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + */ + +function makeEmptyFunction(arg) { + return function () { + return arg; + }; +} + +/** + * This function accepts and discards inputs; it has no side effects. This is + * primarily useful idiomatically for overridable function endpoints which + * always need to be callable, since JS lacks a null-call idiom ala Cocoa. + */ +var emptyFunction = function emptyFunction() {}; + +emptyFunction.thatReturns = makeEmptyFunction; +emptyFunction.thatReturnsFalse = makeEmptyFunction(false); +emptyFunction.thatReturnsTrue = makeEmptyFunction(true); +emptyFunction.thatReturnsNull = makeEmptyFunction(null); +emptyFunction.thatReturnsThis = function () { + return this; +}; +emptyFunction.thatReturnsArgument = function (arg) { + return arg; +}; + +module.exports = emptyFunction; + +/***/ }), +/* 41 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + + + +var getDocumentScrollElement = __webpack_require__(171); +var getUnboundedScrollPosition = __webpack_require__(175); + +/** + * Gets the scroll position of the supplied element or window. + * + * The return values are bounded. This means that if the scroll position is + * negative or exceeds the element boundaries (which is possible using inertial + * scrolling), you will get zero or the maximum scroll position, respectively. + * + * If you need the unbound scroll position, use `getUnboundedScrollPosition`. + * + * @param {DOMWindow|DOMElement} scrollable + * @return {object} Map with `x` and `y` keys. + */ +function getScrollPosition(scrollable) { + var documentScrollElement = getDocumentScrollElement(scrollable.ownerDocument || scrollable.document); + if (scrollable.Window && scrollable instanceof scrollable.Window) { + scrollable = documentScrollElement; + } + var scrollPosition = getUnboundedScrollPosition(scrollable); + + var viewport = scrollable === documentScrollElement ? scrollable.ownerDocument.documentElement : scrollable; + + var xMax = scrollable.scrollWidth - viewport.clientWidth; + var yMax = scrollable.scrollHeight - viewport.clientHeight; + + scrollPosition.x = Math.max(0, Math.min(scrollPosition.x, xMax)); + scrollPosition.y = Math.max(0, Math.min(scrollPosition.y, yMax)); + + return scrollPosition; +} + +module.exports = getScrollPosition; + +/***/ }), +/* 42 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +var printWarning = function() {}; + +if (process.env.NODE_ENV !== 'production') { + var ReactPropTypesSecret = __webpack_require__(43); + var loggedTypeFailures = {}; + + printWarning = function(text) { + var message = 'Warning: ' + text; + if (typeof console !== 'undefined') { + console.error(message); + } + try { + // --- Welcome to debugging React --- + // This error was thrown as a convenience so that you can use this stack + // to find the callsite that caused this warning to fire. + throw new Error(message); + } catch (x) {} + }; +} + +/** + * Assert that the values match with the type specs. + * Error messages are memorized and will only be shown once. + * + * @param {object} typeSpecs Map of name to a ReactPropType + * @param {object} values Runtime values that need to be type-checked + * @param {string} location e.g. "prop", "context", "child context" + * @param {string} componentName Name of the component for error messages. + * @param {?Function} getStack Returns the component stack. + * @private + */ +function checkPropTypes(typeSpecs, values, location, componentName, getStack) { + if (process.env.NODE_ENV !== 'production') { + for (var typeSpecName in typeSpecs) { + if (typeSpecs.hasOwnProperty(typeSpecName)) { + var error; + // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + var err = Error( + (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + ); + err.name = 'Invariant Violation'; + throw err; + } + error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); + } catch (ex) { + error = ex; + } + if (error && !(error instanceof Error)) { + printWarning( + (componentName || 'React class') + ': type specification of ' + + location + ' `' + typeSpecName + '` is invalid; the type checker ' + + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + + 'You may have forgotten to pass an argument to the type checker ' + + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + + 'shape all require an argument).' + ) + + } + if (error instanceof Error && !(error.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error.message] = true; + + var stack = getStack ? getStack() : ''; + + printWarning( + 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') + ); + } + } + } + } +} + +module.exports = checkPropTypes; + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; + +module.exports = ReactPropTypesSecret; + + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +exports.default = compareObjects; +function compareObjects(objA, objB) { + var keys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + + if (objA === objB) { + return false; + } + + var aKeys = Object.keys(objA); + var bKeys = Object.keys(objB); + + if (aKeys.length !== bKeys.length) { + return true; + } + + var keysMap = {}; + var i = void 0, + len = void 0; + + for (i = 0, len = keys.length; i < len; i++) { + keysMap[keys[i]] = true; + } + + for (i = 0, len = aKeys.length; i < len; i++) { + var key = aKeys[i]; + var aValue = objA[key]; + var bValue = objB[key]; + + if (aValue === bValue) { + continue; + } + + if (!keysMap[key] || aValue === null || bValue === null || (typeof aValue === 'undefined' ? 'undefined' : _typeof(aValue)) !== 'object' || (typeof bValue === 'undefined' ? 'undefined' : _typeof(bValue)) !== 'object') { + return true; + } + + var aValueKeys = Object.keys(aValue); + var bValueKeys = Object.keys(bValue); + + if (aValueKeys.length !== bValueKeys.length) { + return true; + } + + for (var n = 0, length = aValueKeys.length; n < length; n++) { + var aValueKey = aValueKeys[n]; + + if (aValue[aValueKey] !== bValue[aValueKey]) { + return true; + } + } + } + + return false; +} + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + */ + +function makeEmptyFunction(arg) { + return function () { + return arg; + }; +} + +/** + * This function accepts and discards inputs; it has no side effects. This is + * primarily useful idiomatically for overridable function endpoints which + * always need to be callable, since JS lacks a null-call idiom ala Cocoa. + */ +var emptyFunction = function emptyFunction() {}; + +emptyFunction.thatReturns = makeEmptyFunction; +emptyFunction.thatReturnsFalse = makeEmptyFunction(false); +emptyFunction.thatReturnsTrue = makeEmptyFunction(true); +emptyFunction.thatReturnsNull = makeEmptyFunction(null); +emptyFunction.thatReturnsThis = function () { + return this; +}; +emptyFunction.thatReturnsArgument = function (arg) { + return arg; +}; + +module.exports = emptyFunction; + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + */ + +function makeEmptyFunction(arg) { + return function () { + return arg; + }; +} + +/** + * This function accepts and discards inputs; it has no side effects. This is + * primarily useful idiomatically for overridable function endpoints which + * always need to be callable, since JS lacks a null-call idiom ala Cocoa. + */ +var emptyFunction = function emptyFunction() {}; + +emptyFunction.thatReturns = makeEmptyFunction; +emptyFunction.thatReturnsFalse = makeEmptyFunction(false); +emptyFunction.thatReturnsTrue = makeEmptyFunction(true); +emptyFunction.thatReturnsNull = makeEmptyFunction(null); +emptyFunction.thatReturnsThis = function () { + return this; +}; +emptyFunction.thatReturnsArgument = function (arg) { + return arg; +}; + +module.exports = emptyFunction; + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SecondaryButton = exports.CloseButton = undefined; + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Button = function Button(_ref) { + var isActive = _ref.isActive, + classes = _ref.classes, + label = _ref.label, + onClick = _ref.onClick; + + var buttonClasses = classes.slice(); + + buttonClasses.push('button'); + if (!isActive) { + buttonClasses.push('button--disabled'); + } + + return _react2.default.createElement( + 'button', + { + type: 'button', + onClick: onClick, + className: buttonClasses.join(' ') + }, + label + ); +}; + +Button.defaultProps = { + isActive: true, + classes: [] +}; + +Button.propTypes = { + isActive: _propTypes2.default.bool, + classes: _propTypes2.default.arrayOf(_propTypes2.default.string), + label: _propTypes2.default.string.isRequired, + onClick: _propTypes2.default.func.isRequired +}; + +var CloseButton = function CloseButton(_ref2) { + var onClick = _ref2.onClick; + + var classes = ['close', 'icon', 'text-replace', 'icon-cross']; + + return _react2.default.createElement(Button, { classes: classes, onClick: onClick, label: 'x' }); +}; + +CloseButton.propTypes = { + onClick: _propTypes2.default.func.isRequired +}; + +var SecondaryButton = function SecondaryButton(_ref3) { + var label = _ref3.label, + onClick = _ref3.onClick; + + var classes = ['action-choose', 'button-small', 'button-secondary']; + + return _react2.default.createElement(Button, { classes: classes, onClick: onClick, label: label }); +}; + +SecondaryButton.propTypes = { + label: _propTypes2.default.string.isRequired, + onClick: _propTypes2.default.func.isRequired +}; + +exports.default = Button; +exports.CloseButton = CloseButton; +exports.SecondaryButton = SecondaryButton; + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +// Translation function. +var tr = exports.tr = function tr(defaultTranslations, customTranslations, key) { + if (customTranslations && key in customTranslations) { + return customTranslations[key]; + } + + if (key in defaultTranslations) { + return defaultTranslations[key]; + } + + return key.replace(/_/g, ' '); +}; + +var pluralize = exports.pluralize = function pluralize(defaultTranslations, customTranslations, singularKey, pluralKey, count) { + var singular = tr(defaultTranslations, customTranslations, singularKey); + var plural = tr(defaultTranslations, customTranslations, pluralKey); + + return count === 1 ? singular : plural; +}; + +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule BlockTree + * @format + * + */ + + + +var Immutable = __webpack_require__(1); + +var emptyFunction = __webpack_require__(40); +var findRangesImmutable = __webpack_require__(21); + +var List = Immutable.List, + Repeat = Immutable.Repeat, + Record = Immutable.Record; + + +var returnTrue = emptyFunction.thatReturnsTrue; + +var FINGERPRINT_DELIMITER = '-'; + +var defaultLeafRange = { + start: null, + end: null +}; + +var LeafRange = Record(defaultLeafRange); + +var defaultDecoratorRange = { + start: null, + end: null, + decoratorKey: null, + leaves: null +}; + +var DecoratorRange = Record(defaultDecoratorRange); + +var BlockTree = { + /** + * Generate a block tree for a given ContentBlock/decorator pair. + */ + generate: function generate(contentState, block, decorator) { + var textLength = block.getLength(); + if (!textLength) { + return List.of(new DecoratorRange({ + start: 0, + end: 0, + decoratorKey: null, + leaves: List.of(new LeafRange({ start: 0, end: 0 })) + })); + } + + var leafSets = []; + var decorations = decorator ? decorator.getDecorations(block, contentState) : List(Repeat(null, textLength)); + + var chars = block.getCharacterList(); + + findRangesImmutable(decorations, areEqual, returnTrue, function (start, end) { + leafSets.push(new DecoratorRange({ + start: start, + end: end, + decoratorKey: decorations.get(start), + leaves: generateLeaves(chars.slice(start, end).toList(), start) + })); + }); + + return List(leafSets); + }, + + /** + * Create a string representation of the given tree map. This allows us + * to rapidly determine whether a tree has undergone a significant + * structural change. + */ + getFingerprint: function getFingerprint(tree) { + return tree.map(function (leafSet) { + var decoratorKey = leafSet.get('decoratorKey'); + var fingerprintString = decoratorKey !== null ? decoratorKey + '.' + (leafSet.get('end') - leafSet.get('start')) : ''; + return '' + fingerprintString + '.' + leafSet.get('leaves').size; + }).join(FINGERPRINT_DELIMITER); + } +}; + +/** + * Generate LeafRange records for a given character list. + */ +function generateLeaves(characters, offset) { + var leaves = []; + var inlineStyles = characters.map(function (c) { + return c.getStyle(); + }).toList(); + findRangesImmutable(inlineStyles, areEqual, returnTrue, function (start, end) { + leaves.push(new LeafRange({ + start: start + offset, + end: end + offset + })); + }); + return List(leaves); +} + +function areEqual(a, b) { + return a === b; +} + +module.exports = BlockTree; + +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DefaultDraftInlineStyle + * @format + * + */ + + + +module.exports = { + BOLD: { + fontWeight: 'bold' + }, + + CODE: { + fontFamily: 'monospace', + wordWrap: 'break-word' + }, + + ITALIC: { + fontStyle: 'italic' + }, + + STRIKETHROUGH: { + textDecoration: 'line-through' + }, + + UNDERLINE: { + textDecoration: 'underline' + } +}; + +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule Draft + * @format + * + */ + + + +var AtomicBlockUtils = __webpack_require__(98); +var BlockMapBuilder = __webpack_require__(20); +var CharacterMetadata = __webpack_require__(7); +var CompositeDraftDecorator = __webpack_require__(99); +var ContentBlock = __webpack_require__(15); +var ContentState = __webpack_require__(29); +var DefaultDraftBlockRenderMap = __webpack_require__(30); +var DefaultDraftInlineStyle = __webpack_require__(50); +var DraftEditor = __webpack_require__(101); +var DraftEditorBlock = __webpack_require__(52); +var DraftEntity = __webpack_require__(25); +var DraftModifier = __webpack_require__(6); +var DraftEntityInstance = __webpack_require__(53); +var EditorState = __webpack_require__(3); +var KeyBindingUtil = __webpack_require__(31); +var RichTextEditorUtil = __webpack_require__(56); +var SelectionState = __webpack_require__(18); + +var convertFromDraftStateToRaw = __webpack_require__(120); +var convertFromHTMLToContentBlocks = __webpack_require__(57); +var convertFromRawToDraftState = __webpack_require__(121); +var generateRandomKey = __webpack_require__(13); +var getDefaultKeyBinding = __webpack_require__(58); +var getVisibleSelectionRect = __webpack_require__(144); + +var DraftPublic = { + Editor: DraftEditor, + EditorBlock: DraftEditorBlock, + EditorState: EditorState, + + CompositeDecorator: CompositeDraftDecorator, + Entity: DraftEntity, + EntityInstance: DraftEntityInstance, + + BlockMapBuilder: BlockMapBuilder, + CharacterMetadata: CharacterMetadata, + ContentBlock: ContentBlock, + ContentState: ContentState, + SelectionState: SelectionState, + + AtomicBlockUtils: AtomicBlockUtils, + KeyBindingUtil: KeyBindingUtil, + Modifier: DraftModifier, + RichUtils: RichTextEditorUtil, + + DefaultDraftBlockRenderMap: DefaultDraftBlockRenderMap, + DefaultDraftInlineStyle: DefaultDraftInlineStyle, + + convertFromHTML: convertFromHTMLToContentBlocks, + convertFromRaw: convertFromRawToDraftState, + convertToRaw: convertFromDraftStateToRaw, + genKey: generateRandomKey, + getDefaultKeyBinding: getDefaultKeyBinding, + getVisibleSelectionRect: getVisibleSelectionRect +}; + +module.exports = DraftPublic; + +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEditorBlock.react + * @format + * + */ + + + +var _assign = __webpack_require__(5); + +var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DraftEditorLeaf = __webpack_require__(107); +var DraftOffsetKey = __webpack_require__(26); +var React = __webpack_require__(4); +var ReactDOM = __webpack_require__(17); +var Scroll = __webpack_require__(73); +var Style = __webpack_require__(37); +var UnicodeBidi = __webpack_require__(74); +var UnicodeBidiDirection = __webpack_require__(38); + +var cx = __webpack_require__(19); +var getElementPosition = __webpack_require__(172); +var getScrollPosition = __webpack_require__(41); +var getViewportDimensions = __webpack_require__(176); +var invariant = __webpack_require__(2); +var nullthrows = __webpack_require__(10); + +var SCROLL_BUFFER = 10; + +/** + * Return whether a block overlaps with either edge of the `SelectionState`. + */ +var isBlockOnSelectionEdge = function isBlockOnSelectionEdge(selection, key) { + return selection.getAnchorKey() === key || selection.getFocusKey() === key; +}; + +/** + * The default block renderer for a `DraftEditor` component. + * + * A `DraftEditorBlock` is able to render a given `ContentBlock` to its + * appropriate decorator and inline style components. + */ + +var DraftEditorBlock = function (_React$Component) { + _inherits(DraftEditorBlock, _React$Component); + + function DraftEditorBlock() { + _classCallCheck(this, DraftEditorBlock); + + return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); + } + + DraftEditorBlock.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { + return this.props.block !== nextProps.block || this.props.tree !== nextProps.tree || this.props.direction !== nextProps.direction || isBlockOnSelectionEdge(nextProps.selection, nextProps.block.getKey()) && nextProps.forceSelection; + }; + + /** + * When a block is mounted and overlaps the selection state, we need to make + * sure that the cursor is visible to match native behavior. This may not + * be the case if the user has pressed `RETURN` or pasted some content, since + * programatically creating these new blocks and setting the DOM selection + * will miss out on the browser natively scrolling to that position. + * + * To replicate native behavior, if the block overlaps the selection state + * on mount, force the scroll position. Check the scroll state of the scroll + * parent, and adjust it to align the entire block to the bottom of the + * scroll parent. + */ + + + DraftEditorBlock.prototype.componentDidMount = function componentDidMount() { + var selection = this.props.selection; + var endKey = selection.getEndKey(); + if (!selection.getHasFocus() || endKey !== this.props.block.getKey()) { + return; + } + + var blockNode = ReactDOM.findDOMNode(this); + var scrollParent = Style.getScrollParent(blockNode); + var scrollPosition = getScrollPosition(scrollParent); + var scrollDelta = void 0; + + if (scrollParent === window) { + var nodePosition = getElementPosition(blockNode); + var nodeBottom = nodePosition.y + nodePosition.height; + var viewportHeight = getViewportDimensions().height; + scrollDelta = nodeBottom - viewportHeight; + if (scrollDelta > 0) { + window.scrollTo(scrollPosition.x, scrollPosition.y + scrollDelta + SCROLL_BUFFER); + } + } else { + !(blockNode instanceof HTMLElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'blockNode is not an HTMLElement') : invariant(false) : void 0; + var blockBottom = blockNode.offsetHeight + blockNode.offsetTop; + var scrollBottom = scrollParent.offsetHeight + scrollPosition.y; + scrollDelta = blockBottom - scrollBottom; + if (scrollDelta > 0) { + Scroll.setTop(scrollParent, Scroll.getTop(scrollParent) + scrollDelta + SCROLL_BUFFER); + } + } + }; + + DraftEditorBlock.prototype._renderChildren = function _renderChildren() { + var _this2 = this; + + var block = this.props.block; + var blockKey = block.getKey(); + var text = block.getText(); + var lastLeafSet = this.props.tree.size - 1; + var hasSelection = isBlockOnSelectionEdge(this.props.selection, blockKey); + + return this.props.tree.map(function (leafSet, ii) { + var leavesForLeafSet = leafSet.get('leaves'); + var lastLeaf = leavesForLeafSet.size - 1; + var leaves = leavesForLeafSet.map(function (leaf, jj) { + var offsetKey = DraftOffsetKey.encode(blockKey, ii, jj); + var start = leaf.get('start'); + var end = leaf.get('end'); + return React.createElement(DraftEditorLeaf, { + key: offsetKey, + offsetKey: offsetKey, + block: block, + start: start, + selection: hasSelection ? _this2.props.selection : null, + forceSelection: _this2.props.forceSelection, + text: text.slice(start, end), + styleSet: block.getInlineStyleAt(start), + customStyleMap: _this2.props.customStyleMap, + customStyleFn: _this2.props.customStyleFn, + isLast: ii === lastLeafSet && jj === lastLeaf + }); + }).toArray(); + + var decoratorKey = leafSet.get('decoratorKey'); + if (decoratorKey == null) { + return leaves; + } + + if (!_this2.props.decorator) { + return leaves; + } + + var decorator = nullthrows(_this2.props.decorator); + + var DecoratorComponent = decorator.getComponentForKey(decoratorKey); + if (!DecoratorComponent) { + return leaves; + } + + var decoratorProps = decorator.getPropsForKey(decoratorKey); + var decoratorOffsetKey = DraftOffsetKey.encode(blockKey, ii, 0); + var decoratedText = text.slice(leavesForLeafSet.first().get('start'), leavesForLeafSet.last().get('end')); + + // Resetting dir to the same value on a child node makes Chrome/Firefox + // confused on cursor movement. See http://jsfiddle.net/d157kLck/3/ + var dir = UnicodeBidiDirection.getHTMLDirIfDifferent(UnicodeBidi.getDirection(decoratedText), _this2.props.direction); + + return React.createElement( + DecoratorComponent, + _extends({}, decoratorProps, { + contentState: _this2.props.contentState, + decoratedText: decoratedText, + dir: dir, + key: decoratorOffsetKey, + entityKey: block.getEntityAt(leafSet.get('start')), + offsetKey: decoratorOffsetKey }), + leaves + ); + }).toArray(); + }; + + DraftEditorBlock.prototype.render = function render() { + var _props = this.props, + direction = _props.direction, + offsetKey = _props.offsetKey; + + var className = cx({ + 'public/DraftStyleDefault/block': true, + 'public/DraftStyleDefault/ltr': direction === 'LTR', + 'public/DraftStyleDefault/rtl': direction === 'RTL' + }); + + return React.createElement( + 'div', + { 'data-offset-key': offsetKey, className: className }, + this._renderChildren() + ); + }; + + return DraftEditorBlock; +}(React.Component); + +module.exports = DraftEditorBlock; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEntityInstance + * @legacyServerCallableInstance + * @format + * + */ + + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var Immutable = __webpack_require__(1); + +var Record = Immutable.Record; + + +var DraftEntityInstanceRecord = Record({ + type: 'TOKEN', + mutability: 'IMMUTABLE', + data: Object +}); + +/** + * An instance of a document entity, consisting of a `type` and relevant + * `data`, metadata about the entity. + * + * For instance, a "link" entity might provide a URI, and a "mention" + * entity might provide the mentioned user's ID. These pieces of data + * may be used when rendering the entity as part of a ContentBlock DOM + * representation. For a link, the data would be used as an href for + * the rendered anchor. For a mention, the ID could be used to retrieve + * a hovercard. + */ + +var DraftEntityInstance = function (_DraftEntityInstanceR) { + _inherits(DraftEntityInstance, _DraftEntityInstanceR); + + function DraftEntityInstance() { + _classCallCheck(this, DraftEntityInstance); + + return _possibleConstructorReturn(this, _DraftEntityInstanceR.apply(this, arguments)); + } + + DraftEntityInstance.prototype.getType = function getType() { + return this.get('type'); + }; + + DraftEntityInstance.prototype.getMutability = function getMutability() { + return this.get('mutability'); + }; + + DraftEntityInstance.prototype.getData = function getData() { + return this.get('data'); + }; + + return DraftEntityInstance; +}(DraftEntityInstanceRecord); + +module.exports = DraftEntityInstance; + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftRemovableWord + * @format + * + */ + + + +var TokenizeUtil = __webpack_require__(164); + +var punctuation = TokenizeUtil.getPunctuation(); + +// The apostrophe and curly single quotes behave in a curious way: when +// surrounded on both sides by word characters, they behave as word chars; when +// either neighbor is punctuation or an end of the string, they behave as +// punctuation. +var CHAMELEON_CHARS = '[\'\u2018\u2019]'; + +// Remove the underscore, which should count as part of the removable word. The +// "chameleon chars" also count as punctuation in this regex. +var WHITESPACE_AND_PUNCTUATION = '\\s|(?![_])' + punctuation; + +var DELETE_STRING = '^' + '(?:' + WHITESPACE_AND_PUNCTUATION + ')*' + '(?:' + CHAMELEON_CHARS + '|(?!' + WHITESPACE_AND_PUNCTUATION + ').)*' + '(?:(?!' + WHITESPACE_AND_PUNCTUATION + ').)'; +var DELETE_REGEX = new RegExp(DELETE_STRING); + +var BACKSPACE_STRING = '(?:(?!' + WHITESPACE_AND_PUNCTUATION + ').)' + '(?:' + CHAMELEON_CHARS + '|(?!' + WHITESPACE_AND_PUNCTUATION + ').)*' + '(?:' + WHITESPACE_AND_PUNCTUATION + ')*' + '$'; +var BACKSPACE_REGEX = new RegExp(BACKSPACE_STRING); + +function getRemovableWord(text, isBackward) { + var matches = isBackward ? BACKSPACE_REGEX.exec(text) : DELETE_REGEX.exec(text); + return matches ? matches[0] : text; +} + +var DraftRemovableWord = { + getBackward: function getBackward(text) { + return getRemovableWord(text, true); + }, + + getForward: function getForward(text) { + return getRemovableWord(text, false); + } +}; + +module.exports = DraftRemovableWord; + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftStringKey + * @format + * + */ + + + +var DraftStringKey = { + stringify: function stringify(key) { + return '_' + String(key); + }, + + unstringify: function unstringify(key) { + return key.slice(1); + } +}; + +module.exports = DraftStringKey; + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule RichTextEditorUtil + * @format + * + */ + + + +var DraftModifier = __webpack_require__(6); +var EditorState = __webpack_require__(3); +var SelectionState = __webpack_require__(18); + +var adjustBlockDepthForContentState = __webpack_require__(117); +var nullthrows = __webpack_require__(10); + +var RichTextEditorUtil = { + currentBlockContainsLink: function currentBlockContainsLink(editorState) { + var selection = editorState.getSelection(); + var contentState = editorState.getCurrentContent(); + var entityMap = contentState.getEntityMap(); + return contentState.getBlockForKey(selection.getAnchorKey()).getCharacterList().slice(selection.getStartOffset(), selection.getEndOffset()).some(function (v) { + var entity = v.getEntity(); + return !!entity && entityMap.__get(entity).getType() === 'LINK'; + }); + }, + + getCurrentBlockType: function getCurrentBlockType(editorState) { + var selection = editorState.getSelection(); + return editorState.getCurrentContent().getBlockForKey(selection.getStartKey()).getType(); + }, + + getDataObjectForLinkURL: function getDataObjectForLinkURL(uri) { + return { url: uri.toString() }; + }, + + handleKeyCommand: function handleKeyCommand(editorState, command) { + switch (command) { + case 'bold': + return RichTextEditorUtil.toggleInlineStyle(editorState, 'BOLD'); + case 'italic': + return RichTextEditorUtil.toggleInlineStyle(editorState, 'ITALIC'); + case 'underline': + return RichTextEditorUtil.toggleInlineStyle(editorState, 'UNDERLINE'); + case 'code': + return RichTextEditorUtil.toggleCode(editorState); + case 'backspace': + case 'backspace-word': + case 'backspace-to-start-of-line': + return RichTextEditorUtil.onBackspace(editorState); + case 'delete': + case 'delete-word': + case 'delete-to-end-of-block': + return RichTextEditorUtil.onDelete(editorState); + default: + // they may have custom editor commands; ignore those + return null; + } + }, + + insertSoftNewline: function insertSoftNewline(editorState) { + var contentState = DraftModifier.insertText(editorState.getCurrentContent(), editorState.getSelection(), '\n', editorState.getCurrentInlineStyle(), null); + + var newEditorState = EditorState.push(editorState, contentState, 'insert-characters'); + + return EditorState.forceSelection(newEditorState, contentState.getSelectionAfter()); + }, + + /** + * For collapsed selections at the start of styled blocks, backspace should + * just remove the existing style. + */ + onBackspace: function onBackspace(editorState) { + var selection = editorState.getSelection(); + if (!selection.isCollapsed() || selection.getAnchorOffset() || selection.getFocusOffset()) { + return null; + } + + // First, try to remove a preceding atomic block. + var content = editorState.getCurrentContent(); + var startKey = selection.getStartKey(); + var blockBefore = content.getBlockBefore(startKey); + + if (blockBefore && blockBefore.getType() === 'atomic') { + var blockMap = content.getBlockMap()['delete'](blockBefore.getKey()); + var withoutAtomicBlock = content.merge({ + blockMap: blockMap, + selectionAfter: selection + }); + if (withoutAtomicBlock !== content) { + return EditorState.push(editorState, withoutAtomicBlock, 'remove-range'); + } + } + + // If that doesn't succeed, try to remove the current block style. + var withoutBlockStyle = RichTextEditorUtil.tryToRemoveBlockStyle(editorState); + + if (withoutBlockStyle) { + return EditorState.push(editorState, withoutBlockStyle, 'change-block-type'); + } + + return null; + }, + + onDelete: function onDelete(editorState) { + var selection = editorState.getSelection(); + if (!selection.isCollapsed()) { + return null; + } + + var content = editorState.getCurrentContent(); + var startKey = selection.getStartKey(); + var block = content.getBlockForKey(startKey); + var length = block.getLength(); + + // The cursor is somewhere within the text. Behave normally. + if (selection.getStartOffset() < length) { + return null; + } + + var blockAfter = content.getBlockAfter(startKey); + + if (!blockAfter || blockAfter.getType() !== 'atomic') { + return null; + } + + var atomicBlockTarget = selection.merge({ + focusKey: blockAfter.getKey(), + focusOffset: blockAfter.getLength() + }); + + var withoutAtomicBlock = DraftModifier.removeRange(content, atomicBlockTarget, 'forward'); + + if (withoutAtomicBlock !== content) { + return EditorState.push(editorState, withoutAtomicBlock, 'remove-range'); + } + + return null; + }, + + onTab: function onTab(event, editorState, maxDepth) { + var selection = editorState.getSelection(); + var key = selection.getAnchorKey(); + if (key !== selection.getFocusKey()) { + return editorState; + } + + var content = editorState.getCurrentContent(); + var block = content.getBlockForKey(key); + var type = block.getType(); + if (type !== 'unordered-list-item' && type !== 'ordered-list-item') { + return editorState; + } + + event.preventDefault(); + + // Only allow indenting one level beyond the block above, and only if + // the block above is a list item as well. + var blockAbove = content.getBlockBefore(key); + if (!blockAbove) { + return editorState; + } + + var typeAbove = blockAbove.getType(); + if (typeAbove !== 'unordered-list-item' && typeAbove !== 'ordered-list-item') { + return editorState; + } + + var depth = block.getDepth(); + if (!event.shiftKey && depth === maxDepth) { + return editorState; + } + + maxDepth = Math.min(blockAbove.getDepth() + 1, maxDepth); + + var withAdjustment = adjustBlockDepthForContentState(content, selection, event.shiftKey ? -1 : 1, maxDepth); + + return EditorState.push(editorState, withAdjustment, 'adjust-depth'); + }, + + toggleBlockType: function toggleBlockType(editorState, blockType) { + var selection = editorState.getSelection(); + var startKey = selection.getStartKey(); + var endKey = selection.getEndKey(); + var content = editorState.getCurrentContent(); + var target = selection; + + // Triple-click can lead to a selection that includes offset 0 of the + // following block. The `SelectionState` for this case is accurate, but + // we should avoid toggling block type for the trailing block because it + // is a confusing interaction. + if (startKey !== endKey && selection.getEndOffset() === 0) { + var blockBefore = nullthrows(content.getBlockBefore(endKey)); + endKey = blockBefore.getKey(); + target = target.merge({ + anchorKey: startKey, + anchorOffset: selection.getStartOffset(), + focusKey: endKey, + focusOffset: blockBefore.getLength(), + isBackward: false + }); + } + + var hasAtomicBlock = content.getBlockMap().skipWhile(function (_, k) { + return k !== startKey; + }).reverse().skipWhile(function (_, k) { + return k !== endKey; + }).some(function (v) { + return v.getType() === 'atomic'; + }); + + if (hasAtomicBlock) { + return editorState; + } + + var typeToSet = content.getBlockForKey(startKey).getType() === blockType ? 'unstyled' : blockType; + + return EditorState.push(editorState, DraftModifier.setBlockType(content, target, typeToSet), 'change-block-type'); + }, + + toggleCode: function toggleCode(editorState) { + var selection = editorState.getSelection(); + var anchorKey = selection.getAnchorKey(); + var focusKey = selection.getFocusKey(); + + if (selection.isCollapsed() || anchorKey !== focusKey) { + return RichTextEditorUtil.toggleBlockType(editorState, 'code-block'); + } + + return RichTextEditorUtil.toggleInlineStyle(editorState, 'CODE'); + }, + + /** + * Toggle the specified inline style for the selection. If the + * user's selection is collapsed, apply or remove the style for the + * internal state. If it is not collapsed, apply the change directly + * to the document state. + */ + toggleInlineStyle: function toggleInlineStyle(editorState, inlineStyle) { + var selection = editorState.getSelection(); + var currentStyle = editorState.getCurrentInlineStyle(); + + // If the selection is collapsed, toggle the specified style on or off and + // set the result as the new inline style override. This will then be + // used as the inline style for the next character to be inserted. + if (selection.isCollapsed()) { + return EditorState.setInlineStyleOverride(editorState, currentStyle.has(inlineStyle) ? currentStyle.remove(inlineStyle) : currentStyle.add(inlineStyle)); + } + + // If characters are selected, immediately apply or remove the + // inline style on the document state itself. + var content = editorState.getCurrentContent(); + var newContent; + + // If the style is already present for the selection range, remove it. + // Otherwise, apply it. + if (currentStyle.has(inlineStyle)) { + newContent = DraftModifier.removeInlineStyle(content, selection, inlineStyle); + } else { + newContent = DraftModifier.applyInlineStyle(content, selection, inlineStyle); + } + + return EditorState.push(editorState, newContent, 'change-inline-style'); + }, + + toggleLink: function toggleLink(editorState, targetSelection, entityKey) { + var withoutLink = DraftModifier.applyEntity(editorState.getCurrentContent(), targetSelection, entityKey); + + return EditorState.push(editorState, withoutLink, 'apply-entity'); + }, + + /** + * When a collapsed cursor is at the start of the first styled block, or + * an empty styled block, changes block to 'unstyled'. Returns null if + * block or selection does not meet that criteria. + */ + tryToRemoveBlockStyle: function tryToRemoveBlockStyle(editorState) { + var selection = editorState.getSelection(); + var offset = selection.getAnchorOffset(); + if (selection.isCollapsed() && offset === 0) { + var key = selection.getAnchorKey(); + var content = editorState.getCurrentContent(); + var block = content.getBlockForKey(key); + + var firstBlock = content.getFirstBlock(); + if (block.getLength() > 0 && block !== firstBlock) { + return null; + } + + var type = block.getType(); + var blockBefore = content.getBlockBefore(key); + if (type === 'code-block' && blockBefore && blockBefore.getType() === 'code-block' && blockBefore.getLength() !== 0) { + return null; + } + + if (type !== 'unstyled') { + return DraftModifier.setBlockType(content, selection, 'unstyled'); + } + } + return null; + } +}; + +module.exports = RichTextEditorUtil; + +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule convertFromHTMLToContentBlocks + * @format + * + */ + + + +var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var _knownListItemDepthCl, + _assign = __webpack_require__(5); + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var CharacterMetadata = __webpack_require__(7); +var ContentBlock = __webpack_require__(15); +var ContentBlockNode = __webpack_require__(9); +var DefaultDraftBlockRenderMap = __webpack_require__(30); +var DraftEntity = __webpack_require__(25); +var DraftFeatureFlags = __webpack_require__(14); +var Immutable = __webpack_require__(1); + +var _require = __webpack_require__(1), + Set = _require.Set; + +var URI = __webpack_require__(165); + +var cx = __webpack_require__(19); +var generateRandomKey = __webpack_require__(13); +var getSafeBodyFromHTML = __webpack_require__(63); +var invariant = __webpack_require__(2); +var sanitizeDraftText = __webpack_require__(35); + +var experimentalTreeDataSupport = DraftFeatureFlags.draft_tree_data_support; + +var List = Immutable.List, + OrderedSet = Immutable.OrderedSet; + + +var NBSP = ' '; +var SPACE = ' '; + +// Arbitrary max indent +var MAX_DEPTH = 4; + +// used for replacing characters in HTML +var REGEX_CR = new RegExp('\r', 'g'); +var REGEX_LF = new RegExp('\n', 'g'); +var REGEX_NBSP = new RegExp(NBSP, 'g'); +var REGEX_CARRIAGE = new RegExp(' ?', 'g'); +var REGEX_ZWS = new RegExp('​?', 'g'); + +// https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight +var boldValues = ['bold', 'bolder', '500', '600', '700', '800', '900']; +var notBoldValues = ['light', 'lighter', '100', '200', '300', '400']; + +// Block tag flow is different because LIs do not have +// a deterministic style ;_; +var inlineTags = { + b: 'BOLD', + code: 'CODE', + del: 'STRIKETHROUGH', + em: 'ITALIC', + i: 'ITALIC', + s: 'STRIKETHROUGH', + strike: 'STRIKETHROUGH', + strong: 'BOLD', + u: 'UNDERLINE' +}; + +var knownListItemDepthClasses = (_knownListItemDepthCl = {}, _defineProperty(_knownListItemDepthCl, cx('public/DraftStyleDefault/depth0'), 0), _defineProperty(_knownListItemDepthCl, cx('public/DraftStyleDefault/depth1'), 1), _defineProperty(_knownListItemDepthCl, cx('public/DraftStyleDefault/depth2'), 2), _defineProperty(_knownListItemDepthCl, cx('public/DraftStyleDefault/depth3'), 3), _defineProperty(_knownListItemDepthCl, cx('public/DraftStyleDefault/depth4'), 4), _knownListItemDepthCl); + +var anchorAttr = ['className', 'href', 'rel', 'target', 'title']; + +var imgAttr = ['alt', 'className', 'height', 'src', 'width']; + +var lastBlock = void 0; + +var EMPTY_CHUNK = { + text: '', + inlines: [], + entities: [], + blocks: [] +}; + +var EMPTY_BLOCK = { + children: List(), + depth: 0, + key: '', + type: '' +}; + +var getListBlockType = function getListBlockType(tag, lastList) { + if (tag === 'li') { + return lastList === 'ol' ? 'ordered-list-item' : 'unordered-list-item'; + } + return null; +}; + +var getBlockMapSupportedTags = function getBlockMapSupportedTags(blockRenderMap) { + var unstyledElement = blockRenderMap.get('unstyled').element; + var tags = Set([]); + + blockRenderMap.forEach(function (draftBlock) { + if (draftBlock.aliasedElements) { + draftBlock.aliasedElements.forEach(function (tag) { + tags = tags.add(tag); + }); + } + + tags = tags.add(draftBlock.element); + }); + + return tags.filter(function (tag) { + return tag && tag !== unstyledElement; + }).toArray().sort(); +}; + +// custom element conversions +var getMultiMatchedType = function getMultiMatchedType(tag, lastList, multiMatchExtractor) { + for (var ii = 0; ii < multiMatchExtractor.length; ii++) { + var matchType = multiMatchExtractor[ii](tag, lastList); + if (matchType) { + return matchType; + } + } + return null; +}; + +var getBlockTypeForTag = function getBlockTypeForTag(tag, lastList, blockRenderMap) { + var matchedTypes = blockRenderMap.filter(function (draftBlock) { + return draftBlock.element === tag || draftBlock.wrapper === tag || draftBlock.aliasedElements && draftBlock.aliasedElements.some(function (alias) { + return alias === tag; + }); + }).keySeq().toSet().toArray().sort(); + + // if we dont have any matched type, return unstyled + // if we have one matched type return it + // if we have multi matched types use the multi-match function to gather type + switch (matchedTypes.length) { + case 0: + return 'unstyled'; + case 1: + return matchedTypes[0]; + default: + return getMultiMatchedType(tag, lastList, [getListBlockType]) || 'unstyled'; + } +}; + +var processInlineTag = function processInlineTag(tag, node, currentStyle) { + var styleToCheck = inlineTags[tag]; + if (styleToCheck) { + currentStyle = currentStyle.add(styleToCheck).toOrderedSet(); + } else if (node instanceof HTMLElement) { + var htmlElement = node; + currentStyle = currentStyle.withMutations(function (style) { + var fontWeight = htmlElement.style.fontWeight; + var fontStyle = htmlElement.style.fontStyle; + var textDecoration = htmlElement.style.textDecoration; + + if (boldValues.indexOf(fontWeight) >= 0) { + style.add('BOLD'); + } else if (notBoldValues.indexOf(fontWeight) >= 0) { + style.remove('BOLD'); + } + + if (fontStyle === 'italic') { + style.add('ITALIC'); + } else if (fontStyle === 'normal') { + style.remove('ITALIC'); + } + + if (textDecoration === 'underline') { + style.add('UNDERLINE'); + } + if (textDecoration === 'line-through') { + style.add('STRIKETHROUGH'); + } + if (textDecoration === 'none') { + style.remove('UNDERLINE'); + style.remove('STRIKETHROUGH'); + } + }).toOrderedSet(); + } + return currentStyle; +}; + +var joinChunks = function joinChunks(A, B, experimentalHasNestedBlocks) { + // Sometimes two blocks will touch in the DOM and we need to strip the + // extra delimiter to preserve niceness. + var lastInA = A.text.slice(-1); + var firstInB = B.text.slice(0, 1); + + if (lastInA === '\r' && firstInB === '\r' && !experimentalHasNestedBlocks) { + A.text = A.text.slice(0, -1); + A.inlines.pop(); + A.entities.pop(); + A.blocks.pop(); + } + + // Kill whitespace after blocks + if (lastInA === '\r') { + if (B.text === SPACE || B.text === '\n') { + return A; + } else if (firstInB === SPACE || firstInB === '\n') { + B.text = B.text.slice(1); + B.inlines.shift(); + B.entities.shift(); + } + } + + return { + text: A.text + B.text, + inlines: A.inlines.concat(B.inlines), + entities: A.entities.concat(B.entities), + blocks: A.blocks.concat(B.blocks) + }; +}; + +/** + * Check to see if we have anything like

... to create + * block tags from. If we do, we can use those and ignore
tags. If we + * don't, we can treat
tags as meaningful (unstyled) blocks. + */ +var containsSemanticBlockMarkup = function containsSemanticBlockMarkup(html, blockTags) { + return blockTags.some(function (tag) { + return html.indexOf('<' + tag) !== -1; + }); +}; + +var hasValidLinkText = function hasValidLinkText(link) { + !(link instanceof HTMLAnchorElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Link must be an HTMLAnchorElement.') : invariant(false) : void 0; + var protocol = link.protocol; + return protocol === 'http:' || protocol === 'https:' || protocol === 'mailto:'; +}; + +var getWhitespaceChunk = function getWhitespaceChunk(inEntity) { + var entities = new Array(1); + if (inEntity) { + entities[0] = inEntity; + } + return _extends({}, EMPTY_CHUNK, { + text: SPACE, + inlines: [OrderedSet()], + entities: entities + }); +}; + +var getSoftNewlineChunk = function getSoftNewlineChunk() { + return _extends({}, EMPTY_CHUNK, { + text: '\n', + inlines: [OrderedSet()], + entities: new Array(1) + }); +}; + +var getChunkedBlock = function getChunkedBlock() { + var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + return _extends({}, EMPTY_BLOCK, props); +}; + +var getBlockDividerChunk = function getBlockDividerChunk(block, depth) { + var parentKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + return { + text: '\r', + inlines: [OrderedSet()], + entities: new Array(1), + blocks: [getChunkedBlock({ + parent: parentKey, + key: generateRandomKey(), + type: block, + depth: Math.max(0, Math.min(MAX_DEPTH, depth)) + })] + }; +}; + +/** + * If we're pasting from one DraftEditor to another we can check to see if + * existing list item depth classes are being used and preserve this style + */ +var getListItemDepth = function getListItemDepth(node) { + var depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + Object.keys(knownListItemDepthClasses).some(function (depthClass) { + if (node.classList.contains(depthClass)) { + depth = knownListItemDepthClasses[depthClass]; + } + }); + return depth; +}; + +var genFragment = function genFragment(entityMap, node, inlineStyle, lastList, inBlock, blockTags, depth, blockRenderMap, inEntity, parentKey) { + var lastLastBlock = lastBlock; + var nodeName = node.nodeName.toLowerCase(); + var newEntityMap = entityMap; + var nextBlockType = 'unstyled'; + var newBlock = false; + var inBlockType = inBlock && getBlockTypeForTag(inBlock, lastList, blockRenderMap); + var chunk = _extends({}, EMPTY_CHUNK); + var newChunk = null; + var blockKey = void 0; + + // Base Case + if (nodeName === '#text') { + var _text = node.textContent; + var nodeTextContent = _text.trim(); + + // We should not create blocks for leading spaces that are + // existing around ol/ul and their children list items + if (lastList && nodeTextContent === '' && node.parentElement) { + var parentNodeName = node.parentElement.nodeName.toLowerCase(); + if (parentNodeName === 'ol' || parentNodeName === 'ul') { + return { chunk: _extends({}, EMPTY_CHUNK), entityMap: entityMap }; + } + } + + if (nodeTextContent === '' && inBlock !== 'pre') { + return { chunk: getWhitespaceChunk(inEntity), entityMap: entityMap }; + } + if (inBlock !== 'pre') { + // Can't use empty string because MSWord + _text = _text.replace(REGEX_LF, SPACE); + } + + // save the last block so we can use it later + lastBlock = nodeName; + + return { + chunk: { + text: _text, + inlines: Array(_text.length).fill(inlineStyle), + entities: Array(_text.length).fill(inEntity), + blocks: [] + }, + entityMap: entityMap + }; + } + + // save the last block so we can use it later + lastBlock = nodeName; + + // BR tags + if (nodeName === 'br') { + if (lastLastBlock === 'br' && (!inBlock || inBlockType === 'unstyled')) { + return { + chunk: getBlockDividerChunk('unstyled', depth, parentKey), + entityMap: entityMap + }; + } + return { chunk: getSoftNewlineChunk(), entityMap: entityMap }; + } + + // IMG tags + if (nodeName === 'img' && node instanceof HTMLImageElement && node.attributes.getNamedItem('src') && node.attributes.getNamedItem('src').value) { + var image = node; + var entityConfig = {}; + + imgAttr.forEach(function (attr) { + var imageAttribute = image.getAttribute(attr); + if (imageAttribute) { + entityConfig[attr] = imageAttribute; + } + }); + // Forcing this node to have children because otherwise no entity will be + // created for this node. + // The child text node cannot just have a space or return as content - + // we strip those out. + // See https://github.com/facebook/draft-js/issues/231 for some context. + node.textContent = '\uD83D\uDCF7'; + + // TODO: update this when we remove DraftEntity entirely + inEntity = DraftEntity.__create('IMAGE', 'MUTABLE', entityConfig || {}); + } + + // Inline tags + inlineStyle = processInlineTag(nodeName, node, inlineStyle); + + // Handle lists + if (nodeName === 'ul' || nodeName === 'ol') { + if (lastList) { + depth += 1; + } + lastList = nodeName; + } + + if (!experimentalTreeDataSupport && nodeName === 'li' && node instanceof HTMLElement) { + depth = getListItemDepth(node, depth); + } + + var blockType = getBlockTypeForTag(nodeName, lastList, blockRenderMap); + var inListBlock = lastList && inBlock === 'li' && nodeName === 'li'; + var inBlockOrHasNestedBlocks = (!inBlock || experimentalTreeDataSupport) && blockTags.indexOf(nodeName) !== -1; + + // Block Tags + if (inListBlock || inBlockOrHasNestedBlocks) { + chunk = getBlockDividerChunk(blockType, depth, parentKey); + blockKey = chunk.blocks[0].key; + inBlock = nodeName; + newBlock = !experimentalTreeDataSupport; + } + + // this is required so that we can handle 'ul' and 'ol' + if (inListBlock) { + nextBlockType = lastList === 'ul' ? 'unordered-list-item' : 'ordered-list-item'; + } + + // Recurse through children + var child = node.firstChild; + if (child != null) { + nodeName = child.nodeName.toLowerCase(); + } + + var entityId = null; + + while (child) { + if (child instanceof HTMLAnchorElement && child.href && hasValidLinkText(child)) { + (function () { + var anchor = child; + var entityConfig = {}; + + anchorAttr.forEach(function (attr) { + var anchorAttribute = anchor.getAttribute(attr); + if (anchorAttribute) { + entityConfig[attr] = anchorAttribute; + } + }); + + entityConfig.url = new URI(anchor.href).toString(); + // TODO: update this when we remove DraftEntity completely + entityId = DraftEntity.__create('LINK', 'MUTABLE', entityConfig || {}); + })(); + } else { + entityId = undefined; + } + + var _genFragment = genFragment(newEntityMap, child, inlineStyle, lastList, inBlock, blockTags, depth, blockRenderMap, entityId || inEntity, experimentalTreeDataSupport ? blockKey : null), + generatedChunk = _genFragment.chunk, + maybeUpdatedEntityMap = _genFragment.entityMap; + + newChunk = generatedChunk; + newEntityMap = maybeUpdatedEntityMap; + + chunk = joinChunks(chunk, newChunk, experimentalTreeDataSupport); + var sibling = child.nextSibling; + + // Put in a newline to break up blocks inside blocks + if (!parentKey && sibling && blockTags.indexOf(nodeName) >= 0 && inBlock) { + chunk = joinChunks(chunk, getSoftNewlineChunk()); + } + if (sibling) { + nodeName = sibling.nodeName.toLowerCase(); + } + child = sibling; + } + + if (newBlock) { + chunk = joinChunks(chunk, getBlockDividerChunk(nextBlockType, depth, parentKey)); + } + + return { chunk: chunk, entityMap: newEntityMap }; +}; + +var getChunkForHTML = function getChunkForHTML(html, DOMBuilder, blockRenderMap, entityMap) { + html = html.trim().replace(REGEX_CR, '').replace(REGEX_NBSP, SPACE).replace(REGEX_CARRIAGE, '').replace(REGEX_ZWS, ''); + + var supportedBlockTags = getBlockMapSupportedTags(blockRenderMap); + + var safeBody = DOMBuilder(html); + if (!safeBody) { + return null; + } + lastBlock = null; + + // Sometimes we aren't dealing with content that contains nice semantic + // tags. In this case, use divs to separate everything out into paragraphs + // and hope for the best. + var workingBlocks = containsSemanticBlockMarkup(html, supportedBlockTags) ? supportedBlockTags : ['div']; + + // Start with -1 block depth to offset the fact that we are passing in a fake + // UL block to start with. + var fragment = genFragment(entityMap, safeBody, OrderedSet(), 'ul', null, workingBlocks, -1, blockRenderMap); + + var chunk = fragment.chunk; + var newEntityMap = fragment.entityMap; + + // join with previous block to prevent weirdness on paste + if (chunk.text.indexOf('\r') === 0) { + chunk = { + text: chunk.text.slice(1), + inlines: chunk.inlines.slice(1), + entities: chunk.entities.slice(1), + blocks: chunk.blocks + }; + } + + // Kill block delimiter at the end + if (chunk.text.slice(-1) === '\r') { + chunk.text = chunk.text.slice(0, -1); + chunk.inlines = chunk.inlines.slice(0, -1); + chunk.entities = chunk.entities.slice(0, -1); + chunk.blocks.pop(); + } + + // If we saw no block tags, put an unstyled one in + if (chunk.blocks.length === 0) { + chunk.blocks.push(_extends({}, EMPTY_CHUNK, { + type: 'unstyled', + depth: 0 + })); + } + + // Sometimes we start with text that isn't in a block, which is then + // followed by blocks. Need to fix up the blocks to add in + // an unstyled block for this content + if (chunk.text.split('\r').length === chunk.blocks.length + 1) { + chunk.blocks.unshift({ type: 'unstyled', depth: 0 }); + } + + return { chunk: chunk, entityMap: newEntityMap }; +}; + +var convertChunkToContentBlocks = function convertChunkToContentBlocks(chunk) { + if (!chunk || !chunk.text || !Array.isArray(chunk.blocks)) { + return null; + } + + var initialState = { + cacheRef: {}, + contentBlocks: [] + }; + + var start = 0; + + var rawBlocks = chunk.blocks, + rawInlines = chunk.inlines, + rawEntities = chunk.entities; + + + var BlockNodeRecord = experimentalTreeDataSupport ? ContentBlockNode : ContentBlock; + + return chunk.text.split('\r').reduce(function (acc, textBlock, index) { + // Make absolutely certain that our text is acceptable. + textBlock = sanitizeDraftText(textBlock); + + var block = rawBlocks[index]; + var end = start + textBlock.length; + var inlines = rawInlines.slice(start, end); + var entities = rawEntities.slice(start, end); + var characterList = List(inlines.map(function (style, index) { + var data = { style: style, entity: null }; + if (entities[index]) { + data.entity = entities[index]; + } + return CharacterMetadata.create(data); + })); + start = end + 1; + + var depth = block.depth, + type = block.type, + parent = block.parent; + + + var key = block.key || generateRandomKey(); + var parentTextNodeKey = null; // will be used to store container text nodes + + // childrens add themselves to their parents since we are iterating in order + if (parent) { + var parentIndex = acc.cacheRef[parent]; + var parentRecord = acc.contentBlocks[parentIndex]; + + // if parent has text we need to split it into a separate unstyled element + if (parentRecord.getChildKeys().isEmpty() && parentRecord.getText()) { + var parentCharacterList = parentRecord.getCharacterList(); + var parentText = parentRecord.getText(); + parentTextNodeKey = generateRandomKey(); + + var textNode = new ContentBlockNode({ + key: parentTextNodeKey, + text: parentText, + characterList: parentCharacterList, + parent: parent, + nextSibling: key + }); + + acc.contentBlocks.push(textNode); + + parentRecord = parentRecord.withMutations(function (block) { + block.set('characterList', List()).set('text', '').set('children', parentRecord.children.push(textNode.getKey())); + }); + } + + acc.contentBlocks[parentIndex] = parentRecord.set('children', parentRecord.children.push(key)); + } + + var blockNode = new BlockNodeRecord({ + key: key, + parent: parent, + type: type, + depth: depth, + text: textBlock, + characterList: characterList, + prevSibling: parentTextNodeKey || (index === 0 || rawBlocks[index - 1].parent !== parent ? null : rawBlocks[index - 1].key), + nextSibling: index === rawBlocks.length - 1 || rawBlocks[index + 1].parent !== parent ? null : rawBlocks[index + 1].key + }); + + // insert node + acc.contentBlocks.push(blockNode); + + // cache ref for building links + acc.cacheRef[blockNode.key] = index; + + return acc; + }, initialState).contentBlocks; +}; + +var convertFromHTMLtoContentBlocks = function convertFromHTMLtoContentBlocks(html) { + var DOMBuilder = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getSafeBodyFromHTML; + var blockRenderMap = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DefaultDraftBlockRenderMap; + + // Be ABSOLUTELY SURE that the dom builder you pass here won't execute + // arbitrary code in whatever environment you're running this in. For an + // example of how we try to do this in-browser, see getSafeBodyFromHTML. + + // TODO: replace DraftEntity with an OrderedMap here + var chunkData = getChunkForHTML(html, DOMBuilder, blockRenderMap, DraftEntity); + + if (chunkData == null) { + return null; + } + + var chunk = chunkData.chunk, + entityMap = chunkData.entityMap; + + var contentBlocks = convertChunkToContentBlocks(chunk); + + return { + contentBlocks: contentBlocks, + entityMap: entityMap + }; +}; + +module.exports = convertFromHTMLtoContentBlocks; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getDefaultKeyBinding + * @format + * + */ + + + +var KeyBindingUtil = __webpack_require__(31); +var Keys = __webpack_require__(36); +var UserAgent = __webpack_require__(12); + +var isOSX = UserAgent.isPlatform('Mac OS X'); +var isWindows = UserAgent.isPlatform('Windows'); + +// Firefox on OSX had a bug resulting in navigation instead of cursor movement. +// This bug was fixed in Firefox 29. Feature detection is virtually impossible +// so we just check the version number. See #342765. +var shouldFixFirefoxMovement = isOSX && UserAgent.isBrowser('Firefox < 29'); + +var hasCommandModifier = KeyBindingUtil.hasCommandModifier, + isCtrlKeyCommand = KeyBindingUtil.isCtrlKeyCommand; + + +function shouldRemoveWord(e) { + return isOSX && e.altKey || isCtrlKeyCommand(e); +} + +/** + * Get the appropriate undo/redo command for a Z key command. + */ +function getZCommand(e) { + if (!hasCommandModifier(e)) { + return null; + } + return e.shiftKey ? 'redo' : 'undo'; +} + +function getDeleteCommand(e) { + // Allow default "cut" behavior for Windows on Shift + Delete. + if (isWindows && e.shiftKey) { + return null; + } + return shouldRemoveWord(e) ? 'delete-word' : 'delete'; +} + +function getBackspaceCommand(e) { + if (hasCommandModifier(e) && isOSX) { + return 'backspace-to-start-of-line'; + } + return shouldRemoveWord(e) ? 'backspace-word' : 'backspace'; +} + +/** + * Retrieve a bound key command for the given event. + */ +function getDefaultKeyBinding(e) { + switch (e.keyCode) { + case 66: + // B + return hasCommandModifier(e) ? 'bold' : null; + case 68: + // D + return isCtrlKeyCommand(e) ? 'delete' : null; + case 72: + // H + return isCtrlKeyCommand(e) ? 'backspace' : null; + case 73: + // I + return hasCommandModifier(e) ? 'italic' : null; + case 74: + // J + return hasCommandModifier(e) ? 'code' : null; + case 75: + // K + return !isWindows && isCtrlKeyCommand(e) ? 'secondary-cut' : null; + case 77: + // M + return isCtrlKeyCommand(e) ? 'split-block' : null; + case 79: + // O + return isCtrlKeyCommand(e) ? 'split-block' : null; + case 84: + // T + return isOSX && isCtrlKeyCommand(e) ? 'transpose-characters' : null; + case 85: + // U + return hasCommandModifier(e) ? 'underline' : null; + case 87: + // W + return isOSX && isCtrlKeyCommand(e) ? 'backspace-word' : null; + case 89: + // Y + if (isCtrlKeyCommand(e)) { + return isWindows ? 'redo' : 'secondary-paste'; + } + return null; + case 90: + // Z + return getZCommand(e) || null; + case Keys.RETURN: + return 'split-block'; + case Keys.DELETE: + return getDeleteCommand(e); + case Keys.BACKSPACE: + return getBackspaceCommand(e); + // LEFT/RIGHT handlers serve as a workaround for a Firefox bug. + case Keys.LEFT: + return shouldFixFirefoxMovement && hasCommandModifier(e) ? 'move-selection-to-start-of-block' : null; + case Keys.RIGHT: + return shouldFixFirefoxMovement && hasCommandModifier(e) ? 'move-selection-to-end-of-block' : null; + default: + return null; + } +} + +module.exports = getDefaultKeyBinding; + +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getDraftEditorSelectionWithNodes + * @format + * + */ + + + +var findAncestorOffsetKey = __webpack_require__(32); +var getSelectionOffsetKeyForNode = __webpack_require__(64); +var getUpdatedSelectionState = __webpack_require__(66); +var invariant = __webpack_require__(2); +var nullthrows = __webpack_require__(10); + +/** + * Convert the current selection range to an anchor/focus pair of offset keys + * and values that can be interpreted by components. + */ +function getDraftEditorSelectionWithNodes(editorState, root, anchorNode, anchorOffset, focusNode, focusOffset) { + var anchorIsTextNode = anchorNode.nodeType === Node.TEXT_NODE; + var focusIsTextNode = focusNode.nodeType === Node.TEXT_NODE; + + // If the selection range lies only on text nodes, the task is simple. + // Find the nearest offset-aware elements and use the + // offset values supplied by the selection range. + if (anchorIsTextNode && focusIsTextNode) { + return { + selectionState: getUpdatedSelectionState(editorState, nullthrows(findAncestorOffsetKey(anchorNode)), anchorOffset, nullthrows(findAncestorOffsetKey(focusNode)), focusOffset), + needsRecovery: false + }; + } + + var anchorPoint = null; + var focusPoint = null; + var needsRecovery = true; + + // An element is selected. Convert this selection range into leaf offset + // keys and offset values for consumption at the component level. This + // is common in Firefox, where select-all and triple click behavior leads + // to entire elements being selected. + // + // Note that we use the `needsRecovery` parameter in the callback here. This + // is because when certain elements are selected, the behavior for subsequent + // cursor movement (e.g. via arrow keys) is uncertain and may not match + // expectations at the component level. For example, if an entire
is + // selected and the user presses the right arrow, Firefox keeps the selection + // on the
. If we allow subsequent keypresses to insert characters + // natively, they will be inserted into a browser-created text node to the + // right of that
. This is obviously undesirable. + // + // With the `needsRecovery` flag, we inform the caller that it is responsible + // for manually setting the selection state on the rendered document to + // ensure proper selection state maintenance. + + if (anchorIsTextNode) { + anchorPoint = { + key: nullthrows(findAncestorOffsetKey(anchorNode)), + offset: anchorOffset + }; + focusPoint = getPointForNonTextNode(root, focusNode, focusOffset); + } else if (focusIsTextNode) { + focusPoint = { + key: nullthrows(findAncestorOffsetKey(focusNode)), + offset: focusOffset + }; + anchorPoint = getPointForNonTextNode(root, anchorNode, anchorOffset); + } else { + anchorPoint = getPointForNonTextNode(root, anchorNode, anchorOffset); + focusPoint = getPointForNonTextNode(root, focusNode, focusOffset); + + // If the selection is collapsed on an empty block, don't force recovery. + // This way, on arrow key selection changes, the browser can move the + // cursor from a non-zero offset on one block, through empty blocks, + // to a matching non-zero offset on other text blocks. + if (anchorNode === focusNode && anchorOffset === focusOffset) { + needsRecovery = !!anchorNode.firstChild && anchorNode.firstChild.nodeName !== 'BR'; + } + } + + return { + selectionState: getUpdatedSelectionState(editorState, anchorPoint.key, anchorPoint.offset, focusPoint.key, focusPoint.offset), + needsRecovery: needsRecovery + }; +} + +/** + * Identify the first leaf descendant for the given node. + */ +function getFirstLeaf(node) { + while (node.firstChild && ( + // data-blocks has no offset + node.firstChild instanceof Element && node.firstChild.getAttribute('data-blocks') === 'true' || getSelectionOffsetKeyForNode(node.firstChild))) { + node = node.firstChild; + } + return node; +} + +/** + * Identify the last leaf descendant for the given node. + */ +function getLastLeaf(node) { + while (node.lastChild && ( + // data-blocks has no offset + node.lastChild instanceof Element && node.lastChild.getAttribute('data-blocks') === 'true' || getSelectionOffsetKeyForNode(node.lastChild))) { + node = node.lastChild; + } + return node; +} + +function getPointForNonTextNode(editorRoot, startNode, childOffset) { + var node = startNode; + var offsetKey = findAncestorOffsetKey(node); + + !(offsetKey != null || editorRoot && (editorRoot === node || editorRoot.firstChild === node)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unknown node in selection range.') : invariant(false) : void 0; + + // If the editorRoot is the selection, step downward into the content + // wrapper. + if (editorRoot === node) { + node = node.firstChild; + !(node instanceof Element && node.getAttribute('data-contents') === 'true') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid DraftEditorContents structure.') : invariant(false) : void 0; + if (childOffset > 0) { + childOffset = node.childNodes.length; + } + } + + // If the child offset is zero and we have an offset key, we're done. + // If there's no offset key because the entire editor is selected, + // find the leftmost ("first") leaf in the tree and use that as the offset + // key. + if (childOffset === 0) { + var key = null; + if (offsetKey != null) { + key = offsetKey; + } else { + var firstLeaf = getFirstLeaf(node); + key = nullthrows(getSelectionOffsetKeyForNode(firstLeaf)); + } + return { key: key, offset: 0 }; + } + + var nodeBeforeCursor = node.childNodes[childOffset - 1]; + var leafKey = null; + var textLength = null; + + if (!getSelectionOffsetKeyForNode(nodeBeforeCursor)) { + // Our target node may be a leaf or a text node, in which case we're + // already where we want to be and can just use the child's length as + // our offset. + leafKey = nullthrows(offsetKey); + textLength = getTextContentLength(nodeBeforeCursor); + } else { + // Otherwise, we'll look at the child to the left of the cursor and find + // the last leaf node in its subtree. + var lastLeaf = getLastLeaf(nodeBeforeCursor); + leafKey = nullthrows(getSelectionOffsetKeyForNode(lastLeaf)); + textLength = getTextContentLength(lastLeaf); + } + + return { + key: leafKey, + offset: textLength + }; +} + +/** + * Return the length of a node's textContent, regarding single newline + * characters as zero-length. This allows us to avoid problems with identifying + * the correct selection offset for empty blocks in IE, in which we + * render newlines instead of break tags. + */ +function getTextContentLength(node) { + var textContent = node.textContent; + return textContent === '\n' ? 0 : textContent.length; +} + +module.exports = getDraftEditorSelectionWithNodes; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getFragmentFromSelection + * @format + * + */ + + + +var getContentStateFragment = __webpack_require__(27); + +function getFragmentFromSelection(editorState) { + var selectionState = editorState.getSelection(); + + if (selectionState.isCollapsed()) { + return null; + } + + return getContentStateFragment(editorState.getCurrentContent(), selectionState); +} + +module.exports = getFragmentFromSelection; + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getNextDelimiterBlockKey + * @format + * + * + * This is unstable and not part of the public API and should not be used by + * production systems. This file may be update/removed without notice. + */ + +var ContentBlockNode = __webpack_require__(9); + +var getNextDelimiterBlockKey = function getNextDelimiterBlockKey(block, blockMap) { + var isExperimentalTreeBlock = block instanceof ContentBlockNode; + + if (!isExperimentalTreeBlock) { + return null; + } + + var nextSiblingKey = block.getNextSiblingKey(); + + if (nextSiblingKey) { + return nextSiblingKey; + } + + var parent = block.getParentKey(); + + if (!parent) { + return null; + } + + var nextNonDescendantBlock = blockMap.get(parent); + while (nextNonDescendantBlock && !nextNonDescendantBlock.getNextSiblingKey()) { + var parentKey = nextNonDescendantBlock.getParentKey(); + nextNonDescendantBlock = parentKey ? blockMap.get(parentKey) : null; + } + + if (!nextNonDescendantBlock) { + return null; + } + + return nextNonDescendantBlock.getNextSiblingKey(); +}; + +module.exports = getNextDelimiterBlockKey; + +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getRangeClientRects + * @format + * + */ + + + +var UserAgent = __webpack_require__(12); + +var invariant = __webpack_require__(2); + +var isChrome = UserAgent.isBrowser('Chrome'); + +// In Chrome, the client rects will include the entire bounds of all nodes that +// begin (have a start tag) within the selection, even if the selection does +// not overlap the entire node. To resolve this, we split the range at each +// start tag and join the client rects together. +// https://code.google.com/p/chromium/issues/detail?id=324437 +/* eslint-disable consistent-return */ +function getRangeClientRectsChrome(range) { + var tempRange = range.cloneRange(); + var clientRects = []; + + for (var ancestor = range.endContainer; ancestor != null; ancestor = ancestor.parentNode) { + // If we've climbed up to the common ancestor, we can now use the + // original start point and stop climbing the tree. + var atCommonAncestor = ancestor === range.commonAncestorContainer; + if (atCommonAncestor) { + tempRange.setStart(range.startContainer, range.startOffset); + } else { + tempRange.setStart(tempRange.endContainer, 0); + } + var rects = Array.from(tempRange.getClientRects()); + clientRects.push(rects); + if (atCommonAncestor) { + var _ref; + + clientRects.reverse(); + return (_ref = []).concat.apply(_ref, clientRects); + } + tempRange.setEndBefore(ancestor); + } + + true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Found an unexpected detached subtree when getting range client rects.') : invariant(false) : void 0; +} +/* eslint-enable consistent-return */ + +/** + * Like range.getClientRects() but normalizes for browser bugs. + */ +var getRangeClientRects = isChrome ? getRangeClientRectsChrome : function (range) { + return Array.from(range.getClientRects()); +}; + +module.exports = getRangeClientRects; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getSafeBodyFromHTML + * @format + * + */ + + + +var UserAgent = __webpack_require__(12); + +var invariant = __webpack_require__(2); + +var isOldIE = UserAgent.isBrowser('IE <= 9'); + +// Provides a dom node that will not execute scripts +// https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.createHTMLDocument +// https://developer.mozilla.org/en-US/Add-ons/Code_snippets/HTML_to_DOM + +function getSafeBodyFromHTML(html) { + var doc; + var root = null; + // Provides a safe context + if (!isOldIE && document.implementation && document.implementation.createHTMLDocument) { + doc = document.implementation.createHTMLDocument('foo'); + !doc.documentElement ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing doc.documentElement') : invariant(false) : void 0; + doc.documentElement.innerHTML = html; + root = doc.getElementsByTagName('body')[0]; + } + return root; +} + +module.exports = getSafeBodyFromHTML; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getSelectionOffsetKeyForNode + * @format + * + */ + + + +/** + * Get offset key from a node or it's child nodes. Return the first offset key + * found on the DOM tree of given node. + */ + +function getSelectionOffsetKeyForNode(node) { + if (node instanceof Element) { + var offsetKey = node.getAttribute('data-offset-key'); + if (offsetKey) { + return offsetKey; + } + for (var ii = 0; ii < node.childNodes.length; ii++) { + var childOffsetKey = getSelectionOffsetKeyForNode(node.childNodes[ii]); + if (childOffsetKey) { + return childOffsetKey; + } + } + } + return null; +} + +module.exports = getSelectionOffsetKeyForNode; + +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global, process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getTextContentFromFiles + * @format + * + */ + + + +var invariant = __webpack_require__(2); + +var TEXT_CLIPPING_REGEX = /\.textClipping$/; + +var TEXT_TYPES = { + 'text/plain': true, + 'text/html': true, + 'text/rtf': true +}; + +// Somewhat arbitrary upper bound on text size. Let's not lock up the browser. +var TEXT_SIZE_UPPER_BOUND = 5000; + +/** + * Extract the text content from a file list. + */ +function getTextContentFromFiles(files, callback) { + var readCount = 0; + var results = []; + files.forEach(function ( /*blob*/file) { + readFile(file, function ( /*string*/text) { + readCount++; + text && results.push(text.slice(0, TEXT_SIZE_UPPER_BOUND)); + if (readCount == files.length) { + callback(results.join('\r')); + } + }); + }); +} + +/** + * todo isaac: Do work to turn html/rtf into a content fragment. + */ +function readFile(file, callback) { + if (!global.FileReader || file.type && !(file.type in TEXT_TYPES)) { + callback(''); + return; + } + + if (file.type === '') { + var contents = ''; + // Special-case text clippings, which have an empty type but include + // `.textClipping` in the file name. `readAsText` results in an empty + // string for text clippings, so we force the file name to serve + // as the text value for the file. + if (TEXT_CLIPPING_REGEX.test(file.name)) { + contents = file.name.replace(TEXT_CLIPPING_REGEX, ''); + } + callback(contents); + return; + } + + var reader = new FileReader(); + reader.onload = function () { + var result = reader.result; + !(typeof result === 'string') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'We should be calling "FileReader.readAsText" which returns a string') : invariant(false) : void 0; + callback(result); + }; + reader.onerror = function () { + callback(''); + }; + reader.readAsText(file); +} + +module.exports = getTextContentFromFiles; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11), __webpack_require__(0))) + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getUpdatedSelectionState + * @format + * + */ + + + +var DraftOffsetKey = __webpack_require__(26); + +var nullthrows = __webpack_require__(10); + +function getUpdatedSelectionState(editorState, anchorKey, anchorOffset, focusKey, focusOffset) { + var selection = nullthrows(editorState.getSelection()); + if (process.env.NODE_ENV !== 'production') { + if (!anchorKey || !focusKey) { + /*eslint-disable no-console */ + console.warn('Invalid selection state.', arguments, editorState.toJS()); + /*eslint-enable no-console */ + return selection; + } + } + + var anchorPath = DraftOffsetKey.decode(anchorKey); + var anchorBlockKey = anchorPath.blockKey; + var anchorLeaf = editorState.getBlockTree(anchorBlockKey).getIn([anchorPath.decoratorKey, 'leaves', anchorPath.leafKey]); + + var focusPath = DraftOffsetKey.decode(focusKey); + var focusBlockKey = focusPath.blockKey; + var focusLeaf = editorState.getBlockTree(focusBlockKey).getIn([focusPath.decoratorKey, 'leaves', focusPath.leafKey]); + + var anchorLeafStart = anchorLeaf.get('start'); + var focusLeafStart = focusLeaf.get('start'); + + var anchorBlockOffset = anchorLeaf ? anchorLeafStart + anchorOffset : null; + var focusBlockOffset = focusLeaf ? focusLeafStart + focusOffset : null; + + var areEqual = selection.getAnchorKey() === anchorBlockKey && selection.getAnchorOffset() === anchorBlockOffset && selection.getFocusKey() === focusBlockKey && selection.getFocusOffset() === focusBlockOffset; + + if (areEqual) { + return selection; + } + + var isBackward = false; + if (anchorBlockKey === focusBlockKey) { + var anchorLeafEnd = anchorLeaf.get('end'); + var focusLeafEnd = focusLeaf.get('end'); + if (focusLeafStart === anchorLeafStart && focusLeafEnd === anchorLeafEnd) { + isBackward = focusOffset < anchorOffset; + } else { + isBackward = focusLeafStart < anchorLeafStart; + } + } else { + var startKey = editorState.getCurrentContent().getBlockMap().keySeq().skipUntil(function (v) { + return v === anchorBlockKey || v === focusBlockKey; + }).first(); + isBackward = startKey === focusBlockKey; + } + + return selection.merge({ + anchorKey: anchorBlockKey, + anchorOffset: anchorBlockOffset, + focusKey: focusBlockKey, + focusOffset: focusBlockOffset, + isBackward: isBackward + }); +} + +module.exports = getUpdatedSelectionState; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule insertIntoList + * @format + * + */ + + + +/** + * Maintain persistence for target list when appending and prepending. + */ +function insertIntoList(targetList, toInsert, offset) { + if (offset === targetList.count()) { + toInsert.forEach(function (c) { + targetList = targetList.push(c); + }); + } else if (offset === 0) { + toInsert.reverse().forEach(function (c) { + targetList = targetList.unshift(c); + }); + } else { + var head = targetList.slice(0, offset); + var tail = targetList.slice(offset); + targetList = head.concat(toInsert, tail).toList(); + } + return targetList; +} + +module.exports = insertIntoList; + +/***/ }), +/* 68 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule isSelectionAtLeafStart + * @format + * + */ + + + +function isSelectionAtLeafStart(editorState) { + var selection = editorState.getSelection(); + var anchorKey = selection.getAnchorKey(); + var blockTree = editorState.getBlockTree(anchorKey); + var offset = selection.getStartOffset(); + + var isAtStart = false; + + blockTree.some(function (leafSet) { + if (offset === leafSet.get('start')) { + isAtStart = true; + return true; + } + + if (offset < leafSet.get('end')) { + return leafSet.get('leaves').some(function (leaf) { + var leafStart = leaf.get('start'); + if (offset === leafStart) { + isAtStart = true; + return true; + } + + return false; + }); + } + + return false; + }); + + return isAtStart; +} + +module.exports = isSelectionAtLeafStart; + +/***/ }), +/* 69 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule moveSelectionForward + * @format + * + */ + + + +/** + * Given a collapsed selection, move the focus `maxDistance` forward within + * the selected block. If the selection will go beyond the end of the block, + * move focus to the start of the next block, but no further. + * + * This function is not Unicode-aware, so surrogate pairs will be treated + * as having length 2. + */ +function moveSelectionForward(editorState, maxDistance) { + var selection = editorState.getSelection(); + var key = selection.getStartKey(); + var offset = selection.getStartOffset(); + var content = editorState.getCurrentContent(); + + var focusKey = key; + var focusOffset; + + var block = content.getBlockForKey(key); + + if (maxDistance > block.getText().length - offset) { + focusKey = content.getKeyAfter(key); + focusOffset = 0; + } else { + focusOffset = offset + maxDistance; + } + + return selection.merge({ focusKey: focusKey, focusOffset: focusOffset }); +} + +module.exports = moveSelectionForward; + +/***/ }), +/* 70 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule randomizeBlockMapKeys + * @format + * + */ + + + +var ContentBlockNode = __webpack_require__(9); +var Immutable = __webpack_require__(1); + +var generateRandomKey = __webpack_require__(13); + +var OrderedMap = Immutable.OrderedMap; + + +var randomizeContentBlockNodeKeys = function randomizeContentBlockNodeKeys(blockMap) { + var newKeysRef = {}; + + // we keep track of root blocks in order to update subsequent sibling links + var lastRootBlock = void 0; + + return OrderedMap(blockMap.withMutations(function (blockMapState) { + blockMapState.forEach(function (block, index) { + var oldKey = block.getKey(); + var nextKey = block.getNextSiblingKey(); + var prevKey = block.getPrevSiblingKey(); + var childrenKeys = block.getChildKeys(); + var parentKey = block.getParentKey(); + + // new key that we will use to build linking + var key = generateRandomKey(); + + // we will add it here to re-use it later + newKeysRef[oldKey] = key; + + if (nextKey) { + var nextBlock = blockMapState.get(nextKey); + if (nextBlock) { + blockMapState.setIn([nextKey, 'prevSibling'], key); + } else { + // this can happen when generating random keys for fragments + blockMapState.setIn([oldKey, 'nextSibling'], null); + } + } + + if (prevKey) { + var prevBlock = blockMapState.get(prevKey); + if (prevBlock) { + blockMapState.setIn([prevKey, 'nextSibling'], key); + } else { + // this can happen when generating random keys for fragments + blockMapState.setIn([oldKey, 'prevSibling'], null); + } + } + + if (parentKey && blockMapState.get(parentKey)) { + var parentBlock = blockMapState.get(parentKey); + var parentChildrenList = parentBlock.getChildKeys(); + blockMapState.setIn([parentKey, 'children'], parentChildrenList.set(parentChildrenList.indexOf(block.getKey()), key)); + } else { + // blocks will then be treated as root block nodes + blockMapState.setIn([oldKey, 'parent'], null); + + if (lastRootBlock) { + blockMapState.setIn([lastRootBlock.getKey(), 'nextSibling'], key); + blockMapState.setIn([oldKey, 'prevSibling'], newKeysRef[lastRootBlock.getKey()]); + } + + lastRootBlock = blockMapState.get(oldKey); + } + + childrenKeys.forEach(function (childKey) { + var childBlock = blockMapState.get(childKey); + if (childBlock) { + blockMapState.setIn([childKey, 'parent'], key); + } else { + blockMapState.setIn([oldKey, 'children'], block.getChildKeys().filter(function (child) { + return child !== childKey; + })); + } + }); + }); + }).toArray().map(function (block) { + return [newKeysRef[block.getKey()], block.set('key', newKeysRef[block.getKey()])]; + })); +}; + +var randomizeContentBlockKeys = function randomizeContentBlockKeys(blockMap) { + return OrderedMap(blockMap.toArray().map(function (block) { + var key = generateRandomKey(); + return [key, block.set('key', key)]; + })); +}; + +var randomizeBlockMapKeys = function randomizeBlockMapKeys(blockMap) { + var isTreeBasedBlockMap = blockMap.first() instanceof ContentBlockNode; + + if (!isTreeBasedBlockMap) { + return randomizeContentBlockKeys(blockMap); + } + + return randomizeContentBlockNodeKeys(blockMap); +}; + +module.exports = randomizeBlockMapKeys; + +/***/ }), +/* 71 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule removeEntitiesAtEdges + * @format + * + */ + + + +var CharacterMetadata = __webpack_require__(7); + +var findRangesImmutable = __webpack_require__(21); +var invariant = __webpack_require__(2); + +function removeEntitiesAtEdges(contentState, selectionState) { + var blockMap = contentState.getBlockMap(); + var entityMap = contentState.getEntityMap(); + + var updatedBlocks = {}; + + var startKey = selectionState.getStartKey(); + var startOffset = selectionState.getStartOffset(); + var startBlock = blockMap.get(startKey); + var updatedStart = removeForBlock(entityMap, startBlock, startOffset); + + if (updatedStart !== startBlock) { + updatedBlocks[startKey] = updatedStart; + } + + var endKey = selectionState.getEndKey(); + var endOffset = selectionState.getEndOffset(); + var endBlock = blockMap.get(endKey); + if (startKey === endKey) { + endBlock = updatedStart; + } + + var updatedEnd = removeForBlock(entityMap, endBlock, endOffset); + + if (updatedEnd !== endBlock) { + updatedBlocks[endKey] = updatedEnd; + } + + if (!Object.keys(updatedBlocks).length) { + return contentState.set('selectionAfter', selectionState); + } + + return contentState.merge({ + blockMap: blockMap.merge(updatedBlocks), + selectionAfter: selectionState + }); +} + +function getRemovalRange(characters, key, offset) { + var removalRange; + findRangesImmutable(characters, function (a, b) { + return a.getEntity() === b.getEntity(); + }, function (element) { + return element.getEntity() === key; + }, function (start, end) { + if (start <= offset && end >= offset) { + removalRange = { start: start, end: end }; + } + }); + !(typeof removalRange === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Removal range must exist within character list.') : invariant(false) : void 0; + return removalRange; +} + +function removeForBlock(entityMap, block, offset) { + var chars = block.getCharacterList(); + var charBefore = offset > 0 ? chars.get(offset - 1) : undefined; + var charAfter = offset < chars.count() ? chars.get(offset) : undefined; + var entityBeforeCursor = charBefore ? charBefore.getEntity() : undefined; + var entityAfterCursor = charAfter ? charAfter.getEntity() : undefined; + + if (entityAfterCursor && entityAfterCursor === entityBeforeCursor) { + var entity = entityMap.__get(entityAfterCursor); + if (entity.getMutability() !== 'MUTABLE') { + var _getRemovalRange = getRemovalRange(chars, entityAfterCursor, offset), + start = _getRemovalRange.start, + end = _getRemovalRange.end; + + var current; + while (start < end) { + current = chars.get(start); + chars = chars.set(start, CharacterMetadata.applyEntity(current, null)); + start++; + } + return block.set('characterList', chars); + } + } + + return block; +} + +module.exports = removeEntitiesAtEdges; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 72 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +var PhotosMimeType = __webpack_require__(163); + +var createArrayFromMixed = __webpack_require__(170); +var emptyFunction = __webpack_require__(40); + +var CR_LF_REGEX = new RegExp('\r\n', 'g'); +var LF_ONLY = '\n'; + +var RICH_TEXT_TYPES = { + 'text/rtf': 1, + 'text/html': 1 +}; + +/** + * If DataTransferItem is a file then return the Blob of data. + * + * @param {object} item + * @return {?blob} + */ +function getFileFromDataTransfer(item) { + if (item.kind == 'file') { + return item.getAsFile(); + } +} + +var DataTransfer = function () { + /** + * @param {object} data + */ + function DataTransfer(data) { + _classCallCheck(this, DataTransfer); + + this.data = data; + + // Types could be DOMStringList or array + this.types = data.types ? createArrayFromMixed(data.types) : []; + } + + /** + * Is this likely to be a rich text data transfer? + * + * @return {boolean} + */ + + + DataTransfer.prototype.isRichText = function isRichText() { + // If HTML is available, treat this data as rich text. This way, we avoid + // using a pasted image if it is packaged with HTML -- this may occur with + // pastes from MS Word, for example. However this is only rich text if + // there's accompanying text. + if (this.getHTML() && this.getText()) { + return true; + } + + // When an image is copied from a preview window, you end up with two + // DataTransferItems one of which is a file's metadata as text. Skip those. + if (this.isImage()) { + return false; + } + + return this.types.some(function (type) { + return RICH_TEXT_TYPES[type]; + }); + }; + + /** + * Get raw text. + * + * @return {?string} + */ + + + DataTransfer.prototype.getText = function getText() { + var text; + if (this.data.getData) { + if (!this.types.length) { + text = this.data.getData('Text'); + } else if (this.types.indexOf('text/plain') != -1) { + text = this.data.getData('text/plain'); + } + } + return text ? text.replace(CR_LF_REGEX, LF_ONLY) : null; + }; + + /** + * Get HTML paste data + * + * @return {?string} + */ + + + DataTransfer.prototype.getHTML = function getHTML() { + if (this.data.getData) { + if (!this.types.length) { + return this.data.getData('Text'); + } else if (this.types.indexOf('text/html') != -1) { + return this.data.getData('text/html'); + } + } + }; + + /** + * Is this a link data transfer? + * + * @return {boolean} + */ + + + DataTransfer.prototype.isLink = function isLink() { + return this.types.some(function (type) { + return type.indexOf('Url') != -1 || type.indexOf('text/uri-list') != -1 || type.indexOf('text/x-moz-url'); + }); + }; + + /** + * Get a link url. + * + * @return {?string} + */ + + + DataTransfer.prototype.getLink = function getLink() { + if (this.data.getData) { + if (this.types.indexOf('text/x-moz-url') != -1) { + var url = this.data.getData('text/x-moz-url').split('\n'); + return url[0]; + } + return this.types.indexOf('text/uri-list') != -1 ? this.data.getData('text/uri-list') : this.data.getData('url'); + } + + return null; + }; + + /** + * Is this an image data transfer? + * + * @return {boolean} + */ + + + DataTransfer.prototype.isImage = function isImage() { + var isImage = this.types.some(function (type) { + // Firefox will have a type of application/x-moz-file for images during + // dragging + return type.indexOf('application/x-moz-file') != -1; + }); + + if (isImage) { + return true; + } + + var items = this.getFiles(); + for (var i = 0; i < items.length; i++) { + var type = items[i].type; + if (!PhotosMimeType.isImage(type)) { + return false; + } + } + + return true; + }; + + DataTransfer.prototype.getCount = function getCount() { + if (this.data.hasOwnProperty('items')) { + return this.data.items.length; + } else if (this.data.hasOwnProperty('mozItemCount')) { + return this.data.mozItemCount; + } else if (this.data.files) { + return this.data.files.length; + } + return null; + }; + + /** + * Get files. + * + * @return {array} + */ + + + DataTransfer.prototype.getFiles = function getFiles() { + if (this.data.items) { + // createArrayFromMixed doesn't properly handle DataTransferItemLists. + return Array.prototype.slice.call(this.data.items).map(getFileFromDataTransfer).filter(emptyFunction.thatReturnsArgument); + } else if (this.data.files) { + return Array.prototype.slice.call(this.data.files); + } else { + return []; + } + }; + + /** + * Are there any files to fetch? + * + * @return {boolean} + */ + + + DataTransfer.prototype.hasFiles = function hasFiles() { + return this.getFiles().length > 0; + }; + + return DataTransfer; +}(); + +module.exports = DataTransfer; + +/***/ }), +/* 73 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/** + * @param {DOMElement} element + * @param {DOMDocument} doc + * @return {boolean} + */ +function _isViewportScrollElement(element, doc) { + return !!doc && (element === doc.documentElement || element === doc.body); +} + +/** + * Scroll Module. This class contains 4 simple static functions + * to be used to access Element.scrollTop/scrollLeft properties. + * To solve the inconsistencies between browsers when either + * document.body or document.documentElement is supplied, + * below logic will be used to alleviate the issue: + * + * 1. If 'element' is either 'document.body' or 'document.documentElement, + * get whichever element's 'scroll{Top,Left}' is larger. + * 2. If 'element' is either 'document.body' or 'document.documentElement', + * set the 'scroll{Top,Left}' on both elements. + */ + +var Scroll = { + /** + * @param {DOMElement} element + * @return {number} + */ + getTop: function getTop(element) { + var doc = element.ownerDocument; + return _isViewportScrollElement(element, doc) ? + // In practice, they will either both have the same value, + // or one will be zero and the other will be the scroll position + // of the viewport. So we can use `X || Y` instead of `Math.max(X, Y)` + doc.body.scrollTop || doc.documentElement.scrollTop : element.scrollTop; + }, + + /** + * @param {DOMElement} element + * @param {number} newTop + */ + setTop: function setTop(element, newTop) { + var doc = element.ownerDocument; + if (_isViewportScrollElement(element, doc)) { + doc.body.scrollTop = doc.documentElement.scrollTop = newTop; + } else { + element.scrollTop = newTop; + } + }, + + /** + * @param {DOMElement} element + * @return {number} + */ + getLeft: function getLeft(element) { + var doc = element.ownerDocument; + return _isViewportScrollElement(element, doc) ? doc.body.scrollLeft || doc.documentElement.scrollLeft : element.scrollLeft; + }, + + /** + * @param {DOMElement} element + * @param {number} newLeft + */ + setLeft: function setLeft(element, newLeft) { + var doc = element.ownerDocument; + if (_isViewportScrollElement(element, doc)) { + doc.body.scrollLeft = doc.documentElement.scrollLeft = newLeft; + } else { + element.scrollLeft = newLeft; + } + } +}; + +module.exports = Scroll; + +/***/ }), +/* 74 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + * + */ + +/** + * Basic (stateless) API for text direction detection + * + * Part of our implementation of Unicode Bidirectional Algorithm (UBA) + * Unicode Standard Annex #9 (UAX9) + * http://www.unicode.org/reports/tr9/ + */ + + + +var UnicodeBidiDirection = __webpack_require__(38); + +var invariant = __webpack_require__(2); + +/** + * RegExp ranges of characters with a *Strong* Bidi_Class value. + * + * Data is based on DerivedBidiClass.txt in UCD version 7.0.0. + * + * NOTE: For performance reasons, we only support Unicode's + * Basic Multilingual Plane (BMP) for now. + */ +var RANGE_BY_BIDI_TYPE = { + + L: 'A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u01BA\u01BB' + '\u01BC-\u01BF\u01C0-\u01C3\u01C4-\u0293\u0294\u0295-\u02AF\u02B0-\u02B8' + '\u02BB-\u02C1\u02D0-\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376-\u0377' + '\u037A\u037B-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1' + '\u03A3-\u03F5\u03F7-\u0481\u0482\u048A-\u052F\u0531-\u0556\u0559' + '\u055A-\u055F\u0561-\u0587\u0589\u0903\u0904-\u0939\u093B\u093D' + '\u093E-\u0940\u0949-\u094C\u094E-\u094F\u0950\u0958-\u0961\u0964-\u0965' + '\u0966-\u096F\u0970\u0971\u0972-\u0980\u0982-\u0983\u0985-\u098C' + '\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD' + '\u09BE-\u09C0\u09C7-\u09C8\u09CB-\u09CC\u09CE\u09D7\u09DC-\u09DD' + '\u09DF-\u09E1\u09E6-\u09EF\u09F0-\u09F1\u09F4-\u09F9\u09FA\u0A03' + '\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33' + '\u0A35-\u0A36\u0A38-\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F' + '\u0A72-\u0A74\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0' + '\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0ABE-\u0AC0\u0AC9\u0ACB-\u0ACC\u0AD0' + '\u0AE0-\u0AE1\u0AE6-\u0AEF\u0AF0\u0B02-\u0B03\u0B05-\u0B0C\u0B0F-\u0B10' + '\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40' + '\u0B47-\u0B48\u0B4B-\u0B4C\u0B57\u0B5C-\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F' + '\u0B70\u0B71\u0B72-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95' + '\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9' + '\u0BBE-\u0BBF\u0BC1-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7' + '\u0BE6-\u0BEF\u0BF0-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10' + '\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C59\u0C60-\u0C61' + '\u0C66-\u0C6F\u0C7F\u0C82-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8' + '\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CBE\u0CBF\u0CC0-\u0CC4\u0CC6' + '\u0CC7-\u0CC8\u0CCA-\u0CCB\u0CD5-\u0CD6\u0CDE\u0CE0-\u0CE1\u0CE6-\u0CEF' + '\u0CF1-\u0CF2\u0D02-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D' + '\u0D3E-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D57\u0D60-\u0D61' + '\u0D66-\u0D6F\u0D70-\u0D75\u0D79\u0D7A-\u0D7F\u0D82-\u0D83\u0D85-\u0D96' + '\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF' + '\u0DE6-\u0DEF\u0DF2-\u0DF3\u0DF4\u0E01-\u0E30\u0E32-\u0E33\u0E40-\u0E45' + '\u0E46\u0E4F\u0E50-\u0E59\u0E5A-\u0E5B\u0E81-\u0E82\u0E84\u0E87-\u0E88' + '\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7' + '\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6' + '\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F01-\u0F03\u0F04-\u0F12\u0F13\u0F14' + '\u0F15-\u0F17\u0F1A-\u0F1F\u0F20-\u0F29\u0F2A-\u0F33\u0F34\u0F36\u0F38' + '\u0F3E-\u0F3F\u0F40-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C' + '\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FCF\u0FD0-\u0FD4\u0FD5-\u0FD8' + '\u0FD9-\u0FDA\u1000-\u102A\u102B-\u102C\u1031\u1038\u103B-\u103C\u103F' + '\u1040-\u1049\u104A-\u104F\u1050-\u1055\u1056-\u1057\u105A-\u105D\u1061' + '\u1062-\u1064\u1065-\u1066\u1067-\u106D\u106E-\u1070\u1075-\u1081' + '\u1083-\u1084\u1087-\u108C\u108E\u108F\u1090-\u1099\u109A-\u109C' + '\u109E-\u109F\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FB\u10FC' + '\u10FD-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288' + '\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5' + '\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u1368' + '\u1369-\u137C\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166D-\u166E' + '\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EB-\u16ED\u16EE-\u16F0' + '\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1735-\u1736' + '\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5' + '\u17C7-\u17C8\u17D4-\u17D6\u17D7\u17D8-\u17DA\u17DC\u17E0-\u17E9' + '\u1810-\u1819\u1820-\u1842\u1843\u1844-\u1877\u1880-\u18A8\u18AA' + '\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930-\u1931' + '\u1933-\u1938\u1946-\u194F\u1950-\u196D\u1970-\u1974\u1980-\u19AB' + '\u19B0-\u19C0\u19C1-\u19C7\u19C8-\u19C9\u19D0-\u19D9\u19DA\u1A00-\u1A16' + '\u1A19-\u1A1A\u1A1E-\u1A1F\u1A20-\u1A54\u1A55\u1A57\u1A61\u1A63-\u1A64' + '\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AA6\u1AA7\u1AA8-\u1AAD' + '\u1B04\u1B05-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B44\u1B45-\u1B4B' + '\u1B50-\u1B59\u1B5A-\u1B60\u1B61-\u1B6A\u1B74-\u1B7C\u1B82\u1B83-\u1BA0' + '\u1BA1\u1BA6-\u1BA7\u1BAA\u1BAE-\u1BAF\u1BB0-\u1BB9\u1BBA-\u1BE5\u1BE7' + '\u1BEA-\u1BEC\u1BEE\u1BF2-\u1BF3\u1BFC-\u1BFF\u1C00-\u1C23\u1C24-\u1C2B' + '\u1C34-\u1C35\u1C3B-\u1C3F\u1C40-\u1C49\u1C4D-\u1C4F\u1C50-\u1C59' + '\u1C5A-\u1C77\u1C78-\u1C7D\u1C7E-\u1C7F\u1CC0-\u1CC7\u1CD3\u1CE1' + '\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF2-\u1CF3\u1CF5-\u1CF6\u1D00-\u1D2B' + '\u1D2C-\u1D6A\u1D6B-\u1D77\u1D78\u1D79-\u1D9A\u1D9B-\u1DBF\u1E00-\u1F15' + '\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D' + '\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC' + '\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E' + '\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D' + '\u2124\u2126\u2128\u212A-\u212D\u212F-\u2134\u2135-\u2138\u2139' + '\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2182\u2183-\u2184' + '\u2185-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF' + '\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2C7B\u2C7C-\u2C7D\u2C7E-\u2CE4' + '\u2CEB-\u2CEE\u2CF2-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F' + '\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE' + '\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005\u3006\u3007' + '\u3021-\u3029\u302E-\u302F\u3031-\u3035\u3038-\u303A\u303B\u303C' + '\u3041-\u3096\u309D-\u309E\u309F\u30A1-\u30FA\u30FC-\u30FE\u30FF' + '\u3105-\u312D\u3131-\u318E\u3190-\u3191\u3192-\u3195\u3196-\u319F' + '\u31A0-\u31BA\u31F0-\u31FF\u3200-\u321C\u3220-\u3229\u322A-\u3247' + '\u3248-\u324F\u3260-\u327B\u327F\u3280-\u3289\u328A-\u32B0\u32C0-\u32CB' + '\u32D0-\u32FE\u3300-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DB5' + '\u4E00-\u9FCC\uA000-\uA014\uA015\uA016-\uA48C\uA4D0-\uA4F7\uA4F8-\uA4FD' + '\uA4FE-\uA4FF\uA500-\uA60B\uA60C\uA610-\uA61F\uA620-\uA629\uA62A-\uA62B' + '\uA640-\uA66D\uA66E\uA680-\uA69B\uA69C-\uA69D\uA6A0-\uA6E5\uA6E6-\uA6EF' + '\uA6F2-\uA6F7\uA722-\uA76F\uA770\uA771-\uA787\uA789-\uA78A\uA78B-\uA78E' + '\uA790-\uA7AD\uA7B0-\uA7B1\uA7F7\uA7F8-\uA7F9\uA7FA\uA7FB-\uA801' + '\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA823-\uA824\uA827\uA830-\uA835' + '\uA836-\uA837\uA840-\uA873\uA880-\uA881\uA882-\uA8B3\uA8B4-\uA8C3' + '\uA8CE-\uA8CF\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8F8-\uA8FA\uA8FB\uA900-\uA909' + '\uA90A-\uA925\uA92E-\uA92F\uA930-\uA946\uA952-\uA953\uA95F\uA960-\uA97C' + '\uA983\uA984-\uA9B2\uA9B4-\uA9B5\uA9BA-\uA9BB\uA9BD-\uA9C0\uA9C1-\uA9CD' + '\uA9CF\uA9D0-\uA9D9\uA9DE-\uA9DF\uA9E0-\uA9E4\uA9E6\uA9E7-\uA9EF' + '\uA9F0-\uA9F9\uA9FA-\uA9FE\uAA00-\uAA28\uAA2F-\uAA30\uAA33-\uAA34' + '\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA5F\uAA60-\uAA6F' + '\uAA70\uAA71-\uAA76\uAA77-\uAA79\uAA7A\uAA7B\uAA7D\uAA7E-\uAAAF\uAAB1' + '\uAAB5-\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADC\uAADD\uAADE-\uAADF' + '\uAAE0-\uAAEA\uAAEB\uAAEE-\uAAEF\uAAF0-\uAAF1\uAAF2\uAAF3-\uAAF4\uAAF5' + '\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E' + '\uAB30-\uAB5A\uAB5B\uAB5C-\uAB5F\uAB64-\uAB65\uABC0-\uABE2\uABE3-\uABE4' + '\uABE6-\uABE7\uABE9-\uABEA\uABEB\uABEC\uABF0-\uABF9\uAC00-\uD7A3' + '\uD7B0-\uD7C6\uD7CB-\uD7FB\uE000-\uF8FF\uF900-\uFA6D\uFA70-\uFAD9' + '\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFF6F\uFF70' + '\uFF71-\uFF9D\uFF9E-\uFF9F\uFFA0-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF' + '\uFFD2-\uFFD7\uFFDA-\uFFDC', + + R: '\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05D0-\u05EA\u05EB-\u05EF' + '\u05F0-\u05F2\u05F3-\u05F4\u05F5-\u05FF\u07C0-\u07C9\u07CA-\u07EA' + '\u07F4-\u07F5\u07FA\u07FB-\u07FF\u0800-\u0815\u081A\u0824\u0828' + '\u082E-\u082F\u0830-\u083E\u083F\u0840-\u0858\u085C-\u085D\u085E' + '\u085F-\u089F\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB37\uFB38-\uFB3C' + '\uFB3D\uFB3E\uFB3F\uFB40-\uFB41\uFB42\uFB43-\uFB44\uFB45\uFB46-\uFB4F', + + AL: '\u0608\u060B\u060D\u061B\u061C\u061D\u061E-\u061F\u0620-\u063F\u0640' + '\u0641-\u064A\u066D\u066E-\u066F\u0671-\u06D3\u06D4\u06D5\u06E5-\u06E6' + '\u06EE-\u06EF\u06FA-\u06FC\u06FD-\u06FE\u06FF\u0700-\u070D\u070E\u070F' + '\u0710\u0712-\u072F\u074B-\u074C\u074D-\u07A5\u07B1\u07B2-\u07BF' + '\u08A0-\u08B2\u08B3-\u08E3\uFB50-\uFBB1\uFBB2-\uFBC1\uFBC2-\uFBD2' + '\uFBD3-\uFD3D\uFD40-\uFD4F\uFD50-\uFD8F\uFD90-\uFD91\uFD92-\uFDC7' + '\uFDC8-\uFDCF\uFDF0-\uFDFB\uFDFC\uFDFE-\uFDFF\uFE70-\uFE74\uFE75' + '\uFE76-\uFEFC\uFEFD-\uFEFE' + +}; + +var REGEX_STRONG = new RegExp('[' + RANGE_BY_BIDI_TYPE.L + RANGE_BY_BIDI_TYPE.R + RANGE_BY_BIDI_TYPE.AL + ']'); + +var REGEX_RTL = new RegExp('[' + RANGE_BY_BIDI_TYPE.R + RANGE_BY_BIDI_TYPE.AL + ']'); + +/** + * Returns the first strong character (has Bidi_Class value of L, R, or AL). + * + * @param str A text block; e.g. paragraph, table cell, tag + * @return A character with strong bidi direction, or null if not found + */ +function firstStrongChar(str) { + var match = REGEX_STRONG.exec(str); + return match == null ? null : match[0]; +} + +/** + * Returns the direction of a block of text, based on the direction of its + * first strong character (has Bidi_Class value of L, R, or AL). + * + * @param str A text block; e.g. paragraph, table cell, tag + * @return The resolved direction + */ +function firstStrongCharDir(str) { + var strongChar = firstStrongChar(str); + if (strongChar == null) { + return UnicodeBidiDirection.NEUTRAL; + } + return REGEX_RTL.exec(strongChar) ? UnicodeBidiDirection.RTL : UnicodeBidiDirection.LTR; +} + +/** + * Returns the direction of a block of text, based on the direction of its + * first strong character (has Bidi_Class value of L, R, or AL), or a fallback + * direction, if no strong character is found. + * + * This function is supposed to be used in respect to Higher-Level Protocol + * rule HL1. (http://www.unicode.org/reports/tr9/#HL1) + * + * @param str A text block; e.g. paragraph, table cell, tag + * @param fallback Fallback direction, used if no strong direction detected + * for the block (default = NEUTRAL) + * @return The resolved direction + */ +function resolveBlockDir(str, fallback) { + fallback = fallback || UnicodeBidiDirection.NEUTRAL; + if (!str.length) { + return fallback; + } + var blockDir = firstStrongCharDir(str); + return blockDir === UnicodeBidiDirection.NEUTRAL ? fallback : blockDir; +} + +/** + * Returns the direction of a block of text, based on the direction of its + * first strong character (has Bidi_Class value of L, R, or AL), or a fallback + * direction, if no strong character is found. + * + * NOTE: This function is similar to resolveBlockDir(), but uses the global + * direction as the fallback, so it *always* returns a Strong direction, + * making it useful for integration in places that you need to make the final + * decision, like setting some CSS class. + * + * This function is supposed to be used in respect to Higher-Level Protocol + * rule HL1. (http://www.unicode.org/reports/tr9/#HL1) + * + * @param str A text block; e.g. paragraph, table cell + * @param strongFallback Fallback direction, used if no strong direction + * detected for the block (default = global direction) + * @return The resolved Strong direction + */ +function getDirection(str, strongFallback) { + if (!strongFallback) { + strongFallback = UnicodeBidiDirection.getGlobalDir(); + } + !UnicodeBidiDirection.isStrong(strongFallback) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Fallback direction must be a strong direction') : invariant(false) : void 0; + return resolveBlockDir(str, strongFallback); +} + +/** + * Returns true if getDirection(arguments...) returns LTR. + * + * @param str A text block; e.g. paragraph, table cell + * @param strongFallback Fallback direction, used if no strong direction + * detected for the block (default = global direction) + * @return True if the resolved direction is LTR + */ +function isDirectionLTR(str, strongFallback) { + return getDirection(str, strongFallback) === UnicodeBidiDirection.LTR; +} + +/** + * Returns true if getDirection(arguments...) returns RTL. + * + * @param str A text block; e.g. paragraph, table cell + * @param strongFallback Fallback direction, used if no strong direction + * detected for the block (default = global direction) + * @return True if the resolved direction is RTL + */ +function isDirectionRTL(str, strongFallback) { + return getDirection(str, strongFallback) === UnicodeBidiDirection.RTL; +} + +var UnicodeBidi = { + firstStrongChar: firstStrongChar, + firstStrongCharDir: firstStrongCharDir, + resolveBlockDir: resolveBlockDir, + getDirection: getDirection, + isDirectionLTR: isDirectionLTR, + isDirectionRTL: isDirectionRTL +}; + +module.exports = UnicodeBidi; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 75 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +/* eslint-disable fb-www/typeof-undefined */ + +/** + * Same as document.activeElement but wraps in a try-catch block. In IE it is + * not safe to call document.activeElement if there is nothing focused. + * + * The activeElement will be null only if the document or document body is not + * yet defined. + * + * @param {?DOMDocument} doc Defaults to current document. + * @return {?DOMElement} + */ +function getActiveElement(doc) /*?DOMElement*/{ + doc = doc || (typeof document !== 'undefined' ? document : undefined); + if (typeof doc === 'undefined') { + return null; + } + try { + return doc.activeElement || doc.body; + } catch (e) { + return doc.body; + } +} + +module.exports = getActiveElement; + +/***/ }), +/* 76 */, +/* 77 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + + + +var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); + +/** + * Simple, lightweight module assisting with the detection and context of + * Worker. Helps avoid circular dependencies and allows code to reason about + * whether or not they are in a Worker, even if they never include the main + * `ReactWorker` dependency. + */ +var ExecutionEnvironment = { + + canUseDOM: canUseDOM, + + canUseWorkers: typeof Worker !== 'undefined', + + canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), + + canUseViewport: canUseDOM && !!window.screen, + + isInWorker: !canUseDOM // For now, this is true - might change in the future. + +}; + +module.exports = ExecutionEnvironment; + +/***/ }), +/* 78 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + */ + +var isTextNode = __webpack_require__(201); + +/*eslint-disable no-bitwise */ + +/** + * Checks if a given DOM node contains or is another DOM node. + */ +function containsNode(outerNode, innerNode) { + if (!outerNode || !innerNode) { + return false; + } else if (outerNode === innerNode) { + return true; + } else if (isTextNode(outerNode)) { + return false; + } else if (isTextNode(innerNode)) { + return containsNode(outerNode, innerNode.parentNode); + } else if ('contains' in outerNode) { + return outerNode.contains(innerNode); + } else if (outerNode.compareDocumentPosition) { + return !!(outerNode.compareDocumentPosition(innerNode) & 16); + } else { + return false; + } +} + +module.exports = containsNode; + +/***/ }), +/* 79 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + + + +var emptyObject = {}; + +if (process.env.NODE_ENV !== 'production') { + Object.freeze(emptyObject); +} + +module.exports = emptyObject; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 80 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +/* eslint-disable fb-www/typeof-undefined */ + +/** + * Same as document.activeElement but wraps in a try-catch block. In IE it is + * not safe to call document.activeElement if there is nothing focused. + * + * The activeElement will be null only if the document or document body is not + * yet defined. + * + * @param {?DOMDocument} doc Defaults to current document. + * @return {?DOMElement} + */ +function getActiveElement(doc) /*?DOMElement*/{ + doc = doc || (typeof document !== 'undefined' ? document : undefined); + if (typeof doc === 'undefined') { + return null; + } + try { + return doc.activeElement || doc.body; + } catch (e) { + return doc.body; + } +} + +module.exports = getActiveElement; + +/***/ }), +/* 81 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + + + +/** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + +var validateFormat = function validateFormat(format) {}; + +if (process.env.NODE_ENV !== 'production') { + validateFormat = function validateFormat(format) { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + }; +} + +function invariant(condition, format, a, b, c, d, e, f) { + validateFormat(format); + + if (!condition) { + var error; + if (format === undefined) { + error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error(format.replace(/%s/g, function () { + return args[argIndex++]; + })); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } +} + +module.exports = invariant; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 82 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + * + */ + +/*eslint-disable no-self-compare */ + + + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ +function is(x, y) { + // SameValue algorithm + if (x === y) { + // Steps 1-5, 7-10 + // Steps 6.b-6.e: +0 != -0 + // Added the nonzero y check to make Flow happy, but it is redundant + return x !== 0 || y !== 0 || 1 / x === 1 / y; + } else { + // Step 6.a: NaN == NaN + return x !== x && y !== y; + } +} + +/** + * Performs equality by iterating through keys on an object and returning false + * when any key has values which are not strictly equal between the arguments. + * Returns true when the values of all keys are strictly equal. + */ +function shallowEqual(objA, objB) { + if (is(objA, objB)) { + return true; + } + + if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { + return false; + } + + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + + if (keysA.length !== keysB.length) { + return false; + } + + // Test for A's keys different from B. + for (var i = 0; i < keysA.length; i++) { + if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { + return false; + } + } + + return true; +} + +module.exports = shallowEqual; + +/***/ }), +/* 83 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + + + +var emptyObject = {}; + +if (process.env.NODE_ENV !== 'production') { + Object.freeze(emptyObject); +} + +module.exports = emptyObject; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 84 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + + + +/** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + +var validateFormat = function validateFormat(format) {}; + +if (process.env.NODE_ENV !== 'production') { + validateFormat = function validateFormat(format) { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + }; +} + +function invariant(condition, format, a, b, c, d, e, f) { + validateFormat(format); + + if (!condition) { + var error; + if (format === undefined) { + error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error(format.replace(/%s/g, function () { + return args[argIndex++]; + })); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } +} + +module.exports = invariant; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 85 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _BaseChooser = __webpack_require__(28); + +var _BaseChooser2 = _interopRequireDefault(_BaseChooser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var ModelChooser = function (_React$Component) { + _inherits(ModelChooser, _React$Component); + + function ModelChooser(props) { + _classCallCheck(this, ModelChooser); + + var _this = _possibleConstructorReturn(this, (ModelChooser.__proto__ || Object.getPrototypeOf(ModelChooser)).call(this, props)); + + _this.updateInputValue = _this.updateInputValue.bind(_this); + return _this; + } + + _createClass(ModelChooser, [{ + key: 'updateInputValue', + value: function updateInputValue(item) { + var _props = this.props, + input = _props.input, + pk_name = _props.options.pk_name; + + var newValue = void 0; + + if (item === null) { + // Null state + newValue = null; + } else { + var id = item[pk_name]; + + if (typeof id === 'string') { + // Strings (Eg UUID) + newValue = id.replace(/ /g, ''); + } else { + // Numbers + newValue = id; + } + } + + // TODO: Props mutation WTF? + input.value = newValue; + } + }, { + key: 'render', + value: function render() { + var _props2 = this.props, + options = _props2.options, + input = _props2.input; + + + return _react2.default.createElement(_BaseChooser2.default, _extends({ + initialValue: input.value, + updateInputValue: this.updateInputValue + }, options)); + } + }]); + + return ModelChooser; +}(_react2.default.Component); + +ModelChooser.propTypes = { + // eslint-disable-next-line react/forbid-prop-types + options: _propTypes2.default.object.isRequired, + // eslint-disable-next-line react/forbid-prop-types + input: _propTypes2.default.object.isRequired +}; + +exports.default = ModelChooser; + +/***/ }), +/* 86 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _BaseChooser = __webpack_require__(28); + +var _BaseChooser2 = _interopRequireDefault(_BaseChooser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var RemoteModelChooser = function (_React$Component) { + _inherits(RemoteModelChooser, _React$Component); + + function RemoteModelChooser(props) { + _classCallCheck(this, RemoteModelChooser); + + var _this = _possibleConstructorReturn(this, (RemoteModelChooser.__proto__ || Object.getPrototypeOf(RemoteModelChooser)).call(this, props)); + + _this.updateInputValue = _this.updateInputValue.bind(_this); + return _this; + } + + _createClass(RemoteModelChooser, [{ + key: 'updateInputValue', + value: function updateInputValue(item) { + var _props = this.props, + input = _props.input, + fieldsToSave = _props.options.fields_to_save; + + var newValue = void 0; + + if (item === null) { + // Null state + newValue = null; + } else if (fieldsToSave) { + // Create a new object with only the fields to save + var clone = {}; + fieldsToSave.forEach(function (field) { + clone[field] = item[field]; + }); + newValue = JSON.stringify(clone); + } else { + // Use the whole object. + newValue = JSON.stringify(item); + } + + // TODO: Props mutation WTF? + input.value = newValue; + } + }, { + key: 'render', + value: function render() { + var _props2 = this.props, + input = _props2.input, + options = _props2.options; + + var initialValue = void 0; + try { + // TODO: Should we use safe-parse or something alike? + initialValue = JSON.parse(input.value); + } catch (err) { + initialValue = {}; + } + + return _react2.default.createElement(_BaseChooser2.default, _extends({ + initialValue: initialValue, + updateInputValue: this.updateInputValue + }, options)); + } + }]); + + return RemoteModelChooser; +}(_react2.default.Component); + +RemoteModelChooser.propTypes = { + // eslint-disable-next-line react/forbid-prop-types + options: _propTypes2.default.object.isRequired, + // eslint-disable-next-line react/forbid-prop-types + input: _propTypes2.default.object.isRequired +}; + +exports.default = RemoteModelChooser; + +/***/ }), +/* 87 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var GenericModelEntity = function GenericModelEntity(props) { + console.log(props); + return _react2.default.createElement('span', { + // TODO: Use key to match Python handlers (it has to be unique per entity). + // TODO: Set data correctly. + 'data-foo': 'test' + }, props.children); +}; + +exports.default = GenericModelEntity; + +/***/ }), +/* 88 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _draftJs = __webpack_require__(51); + +var _ModelPicker = __webpack_require__(24); + +var _ModelPicker2 = _interopRequireDefault(_ModelPicker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var API_BASE_URL = '/admin/modelchoosers/api/v1/model/'; + +var ModelSource = function (_React$Component) { + _inherits(ModelSource, _React$Component); + + function ModelSource(props) { + _classCallCheck(this, ModelSource); + + var _this = _possibleConstructorReturn(this, (ModelSource.__proto__ || Object.getPrototypeOf(ModelSource)).call(this, props)); + + _this.onClose = _this.onClose.bind(_this); + _this.onSelected = _this.onSelected.bind(_this); + return _this; + } + + _createClass(ModelSource, [{ + key: 'onClose', + value: function onClose() { + var onClose = this.props.onClose; + + onClose(); + } + }, { + key: 'onSelected', + value: function onSelected(id, data) { + var _props = this.props, + editorState = _props.editorState, + onComplete = _props.onComplete, + _props$entityType = _props.entityType, + content_type = _props$entityType.content_type, + _props$entityType$dis = _props$entityType.display, + display = _props$entityType$dis === undefined ? 'title' : _props$entityType$dis, + _props$entityType$pk_ = _props$entityType.pk_name, + pkName = _props$entityType$pk_ === undefined ? 'uuid' : _props$entityType$pk_, + type = _props$entityType.type; + + var label = void 0; + var entityMutability = void 0; + if (display === '__selection__') { + var selectionState = editorState.getSelection(); + var anchorKey = selectionState.getAnchorKey(); + var currentContent = editorState.getCurrentContent(); + var currentContentBlock = currentContent.getBlockForKey(anchorKey); + var start = selectionState.getStartOffset(); + var end = selectionState.getEndOffset(); + + label = currentContentBlock.getText().slice(start, end); + entityMutability = 'MUTABLE'; + } else { + if (Array.isArray(display)) { + var i = void 0; + for (i = 0; i < display.length; i + 1) { + var fieldName = display[i]; + if (fieldName in data && data[fieldName]) { + label = data[fieldName]; + break; + } + } + } else if (display in data && data[display]) { + label = data[display]; + } + + if (label === undefined) { + label = data[pkName]; + } + entityMutability = 'IMMUTABLE'; + } + var entityData = { + id: id, + label: label, + content_type: content_type + }; + + var contentState = editorState.getCurrentContent(); + var contentStateWithEntity = contentState.createEntity(type, entityMutability, entityData); + var nextState = _draftJs.AtomicBlockUtils.insertAtomicBlock(editorState, contentStateWithEntity.getLastCreatedEntityKey(), ' '); + + onComplete(nextState); + } + }, { + key: 'render', + value: function render() { + var options = this.props.entityType; + + var endpoint = '' + API_BASE_URL + options.content_type; + + return _react2.default.createElement(_ModelPicker2.default, _extends({ + onSelect: this.onSelected, + onClose: this.onClose, + endpoint: endpoint, + value: null, + required: false + }, options)); + } + }]); + + return ModelSource; +}(_react2.default.Component); + +ModelSource.propTypes = { + // eslint-disable-next-line react/forbid-prop-types + editorState: _propTypes2.default.object.isRequired, + onClose: _propTypes2.default.func.isRequired, + onComplete: _propTypes2.default.func.isRequired, + // eslint-disable-next-line react/forbid-prop-types + entityType: _propTypes2.default.object.isRequired +}; + +exports.default = ModelSource; + +/***/ }), +/* 89 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _draftJs = __webpack_require__(51); + +var _ModelPicker = __webpack_require__(24); + +var _ModelPicker2 = _interopRequireDefault(_ModelPicker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var API_BASE_URL = '/admin/modelchoosers/api/v1/remote_model/'; + +var RemoteModelSource = function (_React$Component) { + _inherits(RemoteModelSource, _React$Component); + + function RemoteModelSource(props) { + _classCallCheck(this, RemoteModelSource); + + var _this = _possibleConstructorReturn(this, (RemoteModelSource.__proto__ || Object.getPrototypeOf(RemoteModelSource)).call(this, props)); + + _this.onClose = _this.onClose.bind(_this); + _this.onSelected = _this.onSelected.bind(_this); + return _this; + } + + _createClass(RemoteModelSource, [{ + key: 'onClose', + value: function onClose() { + var onClose = this.props.onClose; + + onClose(); + } + }, { + key: 'onSelected', + value: function onSelected(id, data) { + var _props = this.props, + editorState = _props.editorState, + onComplete = _props.onComplete, + _props$entityType = _props.entityType, + _props$entityType$dis = _props$entityType.display, + display = _props$entityType$dis === undefined ? 'title' : _props$entityType$dis, + fieldsToSave = _props$entityType.fields_to_save, + _props$entityType$pk_ = _props$entityType.pk_name, + pkName = _props$entityType$pk_ === undefined ? 'uuid' : _props$entityType$pk_, + type = _props$entityType.type; + + var label = void 0; + var entityMutability = void 0; + if (display === '__selection__') { + var selectionState = editorState.getSelection(); + var anchorKey = selectionState.getAnchorKey(); + var currentContent = editorState.getCurrentContent(); + var currentContentBlock = currentContent.getBlockForKey(anchorKey); + var start = selectionState.getStartOffset(); + var end = selectionState.getEndOffset(); + + label = currentContentBlock.getText().slice(start, end); + entityMutability = 'MUTABLE'; + } else { + if (Array.isArray(display)) { + var i = void 0; + for (i = 0; i < display.length; i + 1) { + var fieldName = display[i]; + if (fieldName in data && data[fieldName]) { + label = data[fieldName]; + break; + } + } + } else if (display in data && data[display]) { + label = data[display]; + } + + if (label === undefined) { + label = data[pkName]; + } + entityMutability = 'IMMUTABLE'; + } + + var itemData = void 0; + if (fieldsToSave) { + // Create a new object with only the fields to save + var clone = {}; + fieldsToSave.forEach(function (field) { + clone[field] = data[field]; + }); + itemData = clone; + } else { + // Use the whole object. + itemData = data; + } + + var entityData = Object.assign({}, itemData, { + id: id, + label: label + }); + + var contentState = editorState.getCurrentContent(); + var contentStateWithEntity = contentState.createEntity(type, entityMutability, entityData); + var nextState = _draftJs.AtomicBlockUtils.insertAtomicBlock(editorState, contentStateWithEntity.getLastCreatedEntityKey(), ' '); + + onComplete(nextState); + } + }, { + key: 'render', + value: function render() { + var options = this.props.entityType; + + var endpoint = '' + API_BASE_URL + options.content_type; + + return _react2.default.createElement(_ModelPicker2.default, _extends({ + onSelect: this.onSelected, + onClose: this.onClose, + endpoint: endpoint, + value: null, + required: false + }, options)); + } + }]); + + return RemoteModelSource; +}(_react2.default.Component); + +RemoteModelSource.propTypes = { + // eslint-disable-next-line react/forbid-prop-types + editorState: _propTypes2.default.object.isRequired, + onClose: _propTypes2.default.func.isRequired, + onComplete: _propTypes2.default.func.isRequired, + // eslint-disable-next-line react/forbid-prop-types + entityType: _propTypes2.default.object.isRequired +}; + +exports.default = RemoteModelSource; + +/***/ }), +/* 90 */ +/***/ (function(module, exports) { + +// removed by extract-text-webpack-plugin + +/***/ }), +/* 91 */, +/* 92 */, +/* 93 */, +/* 94 */, +/* 95 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _reactAutosuggest = __webpack_require__(187); + +var _reactAutosuggest2 = _interopRequireDefault(_reactAutosuggest); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var getSuggestionValue = function getSuggestionValue(suggestion) { + return suggestion.name; +}; +var renderSuggestion = function renderSuggestion() { + return null; +}; + +var defaultProps = { + filter: '' +}; + +var propTypes = { + onLoadSuggestions: _propTypes2.default.func.isRequired, + onLoadStart: _propTypes2.default.func.isRequired, + onChange: _propTypes2.default.func.isRequired, + endpoint: _propTypes2.default.string.isRequired, + filter: _propTypes2.default.string +}; + +var AutoComplete = function (_Component) { + _inherits(AutoComplete, _Component); + + function AutoComplete(props) { + _classCallCheck(this, AutoComplete); + + var _this = _possibleConstructorReturn(this, (AutoComplete.__proto__ || Object.getPrototypeOf(AutoComplete)).call(this, props)); + + _this.state = { + value: '', + suggestions: [] + }; + + _this.loadSuggestions = _this.loadSuggestions.bind(_this); + _this.onSuggestionsFetchRequested = _this.onSuggestionsFetchRequested.bind(_this); + _this.onSuggestionsClearRequested = _this.onSuggestionsClearRequested.bind(_this); + _this.onChange = _this.onChange.bind(_this); + return _this; + } + + _createClass(AutoComplete, [{ + key: 'onSuggestionsFetchRequested', + value: function onSuggestionsFetchRequested(_ref) { + var value = _ref.value; + var onLoadStart = this.props.onLoadStart; + + onLoadStart(); + this.loadSuggestions(value); + } + }, { + key: 'onSuggestionsClearRequested', + value: function onSuggestionsClearRequested() { + var _this2 = this; + + var onLoadSuggestions = this.props.onLoadSuggestions; + + this.setState({ + loading: false + }, function () { + return onLoadSuggestions(_this2.state.suggestions); + }); + } + }, { + key: 'onChange', + value: function onChange(event, _ref2) { + var newValue = _ref2.newValue; + var onChange = this.props.onChange; + + + this.setState({ + value: newValue + }, function () { + onChange(newValue); + }); + } + }, { + key: 'loadSuggestions', + value: function loadSuggestions(suggestionValue) { + var _this3 = this; + + var _props = this.props, + filter = _props.filter, + endpoint = _props.endpoint, + onLoadSuggestions = _props.onLoadSuggestions; + + var url = endpoint + '/?search=' + suggestionValue + filter; + + fetch(url, { + credentials: 'same-origin' + }).then(function (res) { + return res.json(); + }).then(function (json) { + _this3.setState({ + suggestions: json.results, + loading: false + }, function () { + onLoadSuggestions(json.results); + }); + }); + } + }, { + key: 'render', + value: function render() { + var _state = this.state, + value = _state.value, + suggestions = _state.suggestions; + + + return _react2.default.createElement( + 'div', + null, + _react2.default.createElement(_reactAutosuggest2.default, { + suggestions: suggestions, + onSuggestionsFetchRequested: this.onSuggestionsFetchRequested, + onSuggestionsClearRequested: this.onSuggestionsClearRequested, + getSuggestionValue: getSuggestionValue, + renderSuggestion: renderSuggestion, + inputProps: { + placeholder: 'Type to search', + value: value, + onChange: this.onChange + } + }) + ); + } + }]); + + return AutoComplete; +}(_react.Component); + +AutoComplete.defaultProps = defaultProps; +AutoComplete.propTypes = propTypes; + +exports.default = AutoComplete; + +/***/ }), +/* 96 */, +/* 97 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.initRemoteModelChooser = exports.initModelChooser = exports.RemoteModelChooser = exports.ModelPicker = exports.BaseChooser = undefined; + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _reactDom = __webpack_require__(17); + +var _reactDom2 = _interopRequireDefault(_reactDom); + +__webpack_require__(90); + +var _BaseChooser = __webpack_require__(28); + +var _BaseChooser2 = _interopRequireDefault(_BaseChooser); + +var _ModelChooser = __webpack_require__(85); + +var _ModelChooser2 = _interopRequireDefault(_ModelChooser); + +var _ModelPicker = __webpack_require__(24); + +var _ModelPicker2 = _interopRequireDefault(_ModelPicker); + +var _RemoteModelChooser = __webpack_require__(86); + +var _RemoteModelChooser2 = _interopRequireDefault(_RemoteModelChooser); + +var _ModelSource = __webpack_require__(88); + +var _ModelSource2 = _interopRequireDefault(_ModelSource); + +var _RemoteModelSource = __webpack_require__(89); + +var _RemoteModelSource2 = _interopRequireDefault(_RemoteModelSource); + +var _GenericModelDecorator = __webpack_require__(87); + +var _GenericModelDecorator2 = _interopRequireDefault(_GenericModelDecorator); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var initModelChooser = function initModelChooser(id, data) { + var input = document.getElementById(id); + + if (input) { + var item = input.parentNode; + var control = item.querySelector('[data-model-chooser-mount]'); + _reactDom2.default.render(_react2.default.createElement(_ModelChooser2.default, { input: input, options: data }), control); + } +}; + +var initRemoteModelChooser = function initRemoteModelChooser(id, data) { + var input = document.getElementById(id); + + if (input) { + var item = input.parentNode; + var control = item.querySelector('[data-remote-model-chooser-mount]'); + _reactDom2.default.render(_react2.default.createElement(_RemoteModelChooser2.default, { input: input, options: data }), control); + } +}; + +window.wagtailModelChoosers = {}; +window.wagtailModelChoosers.initModelChooser = initModelChooser; +window.wagtailModelChoosers.initRemoteModelChooser = initRemoteModelChooser; +window.wagtailModelChoosers.ModelSource = _ModelSource2.default; +window.wagtailModelChoosers.RemoteModelSource = _RemoteModelSource2.default; +window.wagtailModelChoosers.GenericModelDecorator = _GenericModelDecorator2.default; + +// Add Sources to WagtailDraftail if available. +// This is for backward compatibility for projects still using WagtailDraftail +// despite upgrading Wagtail 2.0 which has Draftail built-in. +if (Object.prototype.hasOwnProperty.call(window, 'wagtailDraftail')) { + window.wagtailDraftail.registerSources({ ModelSource: _ModelSource2.default, RemoteModelSource: _RemoteModelSource2.default }); +} + +exports.default = _ModelChooser2.default; +exports.BaseChooser = _BaseChooser2.default; +exports.ModelPicker = _ModelPicker2.default; +exports.RemoteModelChooser = _RemoteModelChooser2.default; +exports.initModelChooser = initModelChooser; +exports.initRemoteModelChooser = initRemoteModelChooser; + +/***/ }), +/* 98 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule AtomicBlockUtils + * @format + * + */ + + + +var _assign = __webpack_require__(5); + +var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var BlockMapBuilder = __webpack_require__(20); +var CharacterMetadata = __webpack_require__(7); +var ContentBlock = __webpack_require__(15); +var ContentBlockNode = __webpack_require__(9); +var DraftFeatureFlags = __webpack_require__(14); +var DraftModifier = __webpack_require__(6); +var EditorState = __webpack_require__(3); +var Immutable = __webpack_require__(1); +var SelectionState = __webpack_require__(18); + +var generateRandomKey = __webpack_require__(13); +var moveBlockInContentState = __webpack_require__(158); + +var experimentalTreeDataSupport = DraftFeatureFlags.draft_tree_data_support; +var ContentBlockRecord = experimentalTreeDataSupport ? ContentBlockNode : ContentBlock; + +var List = Immutable.List, + Repeat = Immutable.Repeat; + + +var AtomicBlockUtils = { + insertAtomicBlock: function insertAtomicBlock(editorState, entityKey, character) { + var contentState = editorState.getCurrentContent(); + var selectionState = editorState.getSelection(); + + var afterRemoval = DraftModifier.removeRange(contentState, selectionState, 'backward'); + + var targetSelection = afterRemoval.getSelectionAfter(); + var afterSplit = DraftModifier.splitBlock(afterRemoval, targetSelection); + var insertionTarget = afterSplit.getSelectionAfter(); + + var asAtomicBlock = DraftModifier.setBlockType(afterSplit, insertionTarget, 'atomic'); + + var charData = CharacterMetadata.create({ entity: entityKey }); + + var atomicBlockConfig = { + key: generateRandomKey(), + type: 'atomic', + text: character, + characterList: List(Repeat(charData, character.length)) + }; + + var atomicDividerBlockConfig = { + key: generateRandomKey(), + type: 'unstyled' + }; + + if (experimentalTreeDataSupport) { + atomicBlockConfig = _extends({}, atomicBlockConfig, { + nextSibling: atomicDividerBlockConfig.key + }); + atomicDividerBlockConfig = _extends({}, atomicDividerBlockConfig, { + prevSibling: atomicBlockConfig.key + }); + } + + var fragmentArray = [new ContentBlockRecord(atomicBlockConfig), new ContentBlockRecord(atomicDividerBlockConfig)]; + + var fragment = BlockMapBuilder.createFromArray(fragmentArray); + + var withAtomicBlock = DraftModifier.replaceWithFragment(asAtomicBlock, insertionTarget, fragment); + + var newContent = withAtomicBlock.merge({ + selectionBefore: selectionState, + selectionAfter: withAtomicBlock.getSelectionAfter().set('hasFocus', true) + }); + + return EditorState.push(editorState, newContent, 'insert-fragment'); + }, + + moveAtomicBlock: function moveAtomicBlock(editorState, atomicBlock, targetRange, insertionMode) { + var contentState = editorState.getCurrentContent(); + var selectionState = editorState.getSelection(); + + var withMovedAtomicBlock = void 0; + + if (insertionMode === 'before' || insertionMode === 'after') { + var targetBlock = contentState.getBlockForKey(insertionMode === 'before' ? targetRange.getStartKey() : targetRange.getEndKey()); + + withMovedAtomicBlock = moveBlockInContentState(contentState, atomicBlock, targetBlock, insertionMode); + } else { + var afterRemoval = DraftModifier.removeRange(contentState, targetRange, 'backward'); + + var selectionAfterRemoval = afterRemoval.getSelectionAfter(); + var _targetBlock = afterRemoval.getBlockForKey(selectionAfterRemoval.getFocusKey()); + + if (selectionAfterRemoval.getStartOffset() === 0) { + withMovedAtomicBlock = moveBlockInContentState(afterRemoval, atomicBlock, _targetBlock, 'before'); + } else if (selectionAfterRemoval.getEndOffset() === _targetBlock.getLength()) { + withMovedAtomicBlock = moveBlockInContentState(afterRemoval, atomicBlock, _targetBlock, 'after'); + } else { + var afterSplit = DraftModifier.splitBlock(afterRemoval, selectionAfterRemoval); + + var selectionAfterSplit = afterSplit.getSelectionAfter(); + var _targetBlock2 = afterSplit.getBlockForKey(selectionAfterSplit.getFocusKey()); + + withMovedAtomicBlock = moveBlockInContentState(afterSplit, atomicBlock, _targetBlock2, 'before'); + } + } + + var newContent = withMovedAtomicBlock.merge({ + selectionBefore: selectionState, + selectionAfter: withMovedAtomicBlock.getSelectionAfter().set('hasFocus', true) + }); + + return EditorState.push(editorState, newContent, 'move-block'); + } +}; + +module.exports = AtomicBlockUtils; + +/***/ }), +/* 99 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule CompositeDraftDecorator + * @format + * + */ + + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Immutable = __webpack_require__(1); + +var List = Immutable.List; + + +var DELIMITER = '.'; + +/** + * A CompositeDraftDecorator traverses through a list of DraftDecorator + * instances to identify sections of a ContentBlock that should be rendered + * in a "decorated" manner. For example, hashtags, mentions, and links may + * be intended to stand out visually, be rendered as anchors, etc. + * + * The list of decorators supplied to the constructor will be used in the + * order they are provided. This allows the caller to specify a priority for + * string matching, in case of match collisions among decorators. + * + * For instance, I may have a link with a `#` in its text. Though this section + * of text may match our hashtag decorator, it should not be treated as a + * hashtag. I should therefore list my link DraftDecorator + * before my hashtag DraftDecorator when constructing this composite + * decorator instance. + * + * Thus, when a collision like this is encountered, the earlier match is + * preserved and the new match is discarded. + */ + +var CompositeDraftDecorator = function () { + function CompositeDraftDecorator(decorators) { + _classCallCheck(this, CompositeDraftDecorator); + + // Copy the decorator array, since we use this array order to determine + // precedence of decoration matching. If the array is mutated externally, + // we don't want to be affected here. + this._decorators = decorators.slice(); + } + + CompositeDraftDecorator.prototype.getDecorations = function getDecorations(block, contentState) { + var decorations = Array(block.getText().length).fill(null); + + this._decorators.forEach(function ( /*object*/decorator, /*number*/ii) { + var counter = 0; + var strategy = decorator.strategy; + var callback = function callback( /*number*/start, /*number*/end) { + // Find out if any of our matching range is already occupied + // by another decorator. If so, discard the match. Otherwise, store + // the component key for rendering. + if (canOccupySlice(decorations, start, end)) { + occupySlice(decorations, start, end, ii + DELIMITER + counter); + counter++; + } + }; + strategy(block, callback, contentState); + }); + + return List(decorations); + }; + + CompositeDraftDecorator.prototype.getComponentForKey = function getComponentForKey(key) { + var componentKey = parseInt(key.split(DELIMITER)[0], 10); + return this._decorators[componentKey].component; + }; + + CompositeDraftDecorator.prototype.getPropsForKey = function getPropsForKey(key) { + var componentKey = parseInt(key.split(DELIMITER)[0], 10); + return this._decorators[componentKey].props; + }; + + return CompositeDraftDecorator; +}(); + +/** + * Determine whether we can occupy the specified slice of the decorations + * array. + */ + + +function canOccupySlice(decorations, start, end) { + for (var ii = start; ii < end; ii++) { + if (decorations[ii] != null) { + return false; + } + } + return true; +} + +/** + * Splice the specified component into our decoration array at the desired + * range. + */ +function occupySlice(targetArr, start, end, componentKey) { + for (var ii = start; ii < end; ii++) { + targetArr[ii] = componentKey; + } +} + +module.exports = CompositeDraftDecorator; + +/***/ }), +/* 100 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ContentStateInlineStyle + * @format + * + */ + + + +var CharacterMetadata = __webpack_require__(7); + +var _require = __webpack_require__(1), + Map = _require.Map; + +var ContentStateInlineStyle = { + add: function add(contentState, selectionState, inlineStyle) { + return modifyInlineStyle(contentState, selectionState, inlineStyle, true); + }, + + remove: function remove(contentState, selectionState, inlineStyle) { + return modifyInlineStyle(contentState, selectionState, inlineStyle, false); + } +}; + +function modifyInlineStyle(contentState, selectionState, inlineStyle, addOrRemove) { + var blockMap = contentState.getBlockMap(); + var startKey = selectionState.getStartKey(); + var startOffset = selectionState.getStartOffset(); + var endKey = selectionState.getEndKey(); + var endOffset = selectionState.getEndOffset(); + + var newBlocks = blockMap.skipUntil(function (_, k) { + return k === startKey; + }).takeUntil(function (_, k) { + return k === endKey; + }).concat(Map([[endKey, blockMap.get(endKey)]])).map(function (block, blockKey) { + var sliceStart; + var sliceEnd; + + if (startKey === endKey) { + sliceStart = startOffset; + sliceEnd = endOffset; + } else { + sliceStart = blockKey === startKey ? startOffset : 0; + sliceEnd = blockKey === endKey ? endOffset : block.getLength(); + } + + var chars = block.getCharacterList(); + var current; + while (sliceStart < sliceEnd) { + current = chars.get(sliceStart); + chars = chars.set(sliceStart, addOrRemove ? CharacterMetadata.applyStyle(current, inlineStyle) : CharacterMetadata.removeStyle(current, inlineStyle)); + sliceStart++; + } + + return block.set('characterList', chars); + }); + + return contentState.merge({ + blockMap: blockMap.merge(newBlocks), + selectionBefore: selectionState, + selectionAfter: selectionState + }); +} + +module.exports = ContentStateInlineStyle; + +/***/ }), +/* 101 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEditor.react + * @format + * + * @preventMunge + */ + + + +var _assign = __webpack_require__(5); + +var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DefaultDraftBlockRenderMap = __webpack_require__(30); +var DefaultDraftInlineStyle = __webpack_require__(50); +var DraftEditorCompositionHandler = __webpack_require__(102); +var DraftEditorContents = __webpack_require__(104); +var DraftEditorDragHandler = __webpack_require__(105); +var DraftEditorEditHandler = __webpack_require__(106); +var DraftEditorPlaceholder = __webpack_require__(108); +var EditorState = __webpack_require__(3); +var React = __webpack_require__(4); +var ReactDOM = __webpack_require__(17); +var Scroll = __webpack_require__(73); +var Style = __webpack_require__(37); +var UserAgent = __webpack_require__(12); + +var cx = __webpack_require__(19); +var emptyFunction = __webpack_require__(40); +var generateRandomKey = __webpack_require__(13); +var getDefaultKeyBinding = __webpack_require__(58); +var getScrollPosition = __webpack_require__(41); +var invariant = __webpack_require__(2); +var nullthrows = __webpack_require__(10); + +var isIE = UserAgent.isBrowser('IE'); + +// IE does not support the `input` event on contentEditable, so we can't +// observe spellcheck behavior. +var allowSpellCheck = !isIE; + +// Define a set of handler objects to correspond to each possible `mode` +// of editor behavior. +var handlerMap = { + edit: DraftEditorEditHandler, + composite: DraftEditorCompositionHandler, + drag: DraftEditorDragHandler, + cut: null, + render: null +}; + +/** + * `DraftEditor` is the root editor component. It composes a `contentEditable` + * div, and provides a wide variety of useful function props for managing the + * state of the editor. See `DraftEditorProps` for details. + */ +var DraftEditor = function (_React$Component) { + _inherits(DraftEditor, _React$Component); + + function DraftEditor(props) { + _classCallCheck(this, DraftEditor); + + var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); + + _this.focus = function (scrollPosition) { + var editorState = _this.props.editorState; + + var alreadyHasFocus = editorState.getSelection().getHasFocus(); + var editorNode = ReactDOM.findDOMNode(_this.editor); + + if (!editorNode) { + // once in a while people call 'focus' in a setTimeout, and the node has + // been deleted, so it can be null in that case. + return; + } + + var scrollParent = Style.getScrollParent(editorNode); + + var _ref = scrollPosition || getScrollPosition(scrollParent), + x = _ref.x, + y = _ref.y; + + !(editorNode instanceof HTMLElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'editorNode is not an HTMLElement') : invariant(false) : void 0; + editorNode.focus(); + + // Restore scroll position + if (scrollParent === window) { + window.scrollTo(x, y); + } else { + Scroll.setTop(scrollParent, y); + } + + // On Chrome and Safari, calling focus on contenteditable focuses the + // cursor at the first character. This is something you don't expect when + // you're clicking on an input element but not directly on a character. + // Put the cursor back where it was before the blur. + if (!alreadyHasFocus) { + _this.update(EditorState.forceSelection(editorState, editorState.getSelection())); + } + }; + + _this.blur = function () { + var editorNode = ReactDOM.findDOMNode(_this.editor); + !(editorNode instanceof HTMLElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'editorNode is not an HTMLElement') : invariant(false) : void 0; + editorNode.blur(); + }; + + _this.setMode = function (mode) { + _this._handler = handlerMap[mode]; + }; + + _this.exitCurrentMode = function () { + _this.setMode('edit'); + }; + + _this.restoreEditorDOM = function (scrollPosition) { + _this.setState({ contentsKey: _this.state.contentsKey + 1 }, function () { + _this.focus(scrollPosition); + }); + }; + + _this.setClipboard = function (clipboard) { + _this._clipboard = clipboard; + }; + + _this.getClipboard = function () { + return _this._clipboard; + }; + + _this.update = function (editorState) { + _this._latestEditorState = editorState; + _this.props.onChange(editorState); + }; + + _this.onDragEnter = function () { + _this._dragCount++; + }; + + _this.onDragLeave = function () { + _this._dragCount--; + if (_this._dragCount === 0) { + _this.exitCurrentMode(); + } + }; + + _this._blockSelectEvents = false; + _this._clipboard = null; + _this._handler = null; + _this._dragCount = 0; + _this._editorKey = props.editorKey || generateRandomKey(); + _this._placeholderAccessibilityID = 'placeholder-' + _this._editorKey; + _this._latestEditorState = props.editorState; + _this._latestCommittedEditorState = props.editorState; + + _this._onBeforeInput = _this._buildHandler('onBeforeInput'); + _this._onBlur = _this._buildHandler('onBlur'); + _this._onCharacterData = _this._buildHandler('onCharacterData'); + _this._onCompositionEnd = _this._buildHandler('onCompositionEnd'); + _this._onCompositionStart = _this._buildHandler('onCompositionStart'); + _this._onCopy = _this._buildHandler('onCopy'); + _this._onCut = _this._buildHandler('onCut'); + _this._onDragEnd = _this._buildHandler('onDragEnd'); + _this._onDragOver = _this._buildHandler('onDragOver'); + _this._onDragStart = _this._buildHandler('onDragStart'); + _this._onDrop = _this._buildHandler('onDrop'); + _this._onInput = _this._buildHandler('onInput'); + _this._onFocus = _this._buildHandler('onFocus'); + _this._onKeyDown = _this._buildHandler('onKeyDown'); + _this._onKeyPress = _this._buildHandler('onKeyPress'); + _this._onKeyUp = _this._buildHandler('onKeyUp'); + _this._onMouseDown = _this._buildHandler('onMouseDown'); + _this._onMouseUp = _this._buildHandler('onMouseUp'); + _this._onPaste = _this._buildHandler('onPaste'); + _this._onSelect = _this._buildHandler('onSelect'); + + _this.getEditorKey = function () { + return _this._editorKey; + }; + + // See `restoreEditorDOM()`. + _this.state = { contentsKey: 0 }; + return _this; + } + + /** + * Build a method that will pass the event to the specified handler method. + * This allows us to look up the correct handler function for the current + * editor mode, if any has been specified. + */ + + + /** + * Define proxies that can route events to the current handler. + */ + + + DraftEditor.prototype._buildHandler = function _buildHandler(eventName) { + var _this2 = this; + + return function (e) { + if (!_this2.props.readOnly) { + var method = _this2._handler && _this2._handler[eventName]; + method && method(_this2, e); + } + }; + }; + + DraftEditor.prototype._showPlaceholder = function _showPlaceholder() { + return !!this.props.placeholder && !this.props.editorState.isInCompositionMode() && !this.props.editorState.getCurrentContent().hasText(); + }; + + DraftEditor.prototype._renderPlaceholder = function _renderPlaceholder() { + if (this._showPlaceholder()) { + var placeHolderProps = { + text: nullthrows(this.props.placeholder), + editorState: this.props.editorState, + textAlignment: this.props.textAlignment, + accessibilityID: this._placeholderAccessibilityID + }; + + return React.createElement(DraftEditorPlaceholder, placeHolderProps); + } + return null; + }; + + DraftEditor.prototype.render = function render() { + var _this3 = this; + + var _props = this.props, + blockRenderMap = _props.blockRenderMap, + blockRendererFn = _props.blockRendererFn, + blockStyleFn = _props.blockStyleFn, + customStyleFn = _props.customStyleFn, + customStyleMap = _props.customStyleMap, + editorState = _props.editorState, + readOnly = _props.readOnly, + textAlignment = _props.textAlignment, + textDirectionality = _props.textDirectionality; + + + var rootClass = cx({ + 'DraftEditor/root': true, + 'DraftEditor/alignLeft': textAlignment === 'left', + 'DraftEditor/alignRight': textAlignment === 'right', + 'DraftEditor/alignCenter': textAlignment === 'center' + }); + + var contentStyle = { + outline: 'none', + // fix parent-draggable Safari bug. #1326 + userSelect: 'text', + WebkitUserSelect: 'text', + whiteSpace: 'pre-wrap', + wordWrap: 'break-word' + }; + + // The aria-expanded and aria-haspopup properties should only be rendered + // for a combobox. + var ariaRole = this.props.role || 'textbox'; + var ariaExpanded = ariaRole === 'combobox' ? !!this.props.ariaExpanded : null; + + var editorContentsProps = { + blockRenderMap: blockRenderMap, + blockRendererFn: blockRendererFn, + blockStyleFn: blockStyleFn, + customStyleMap: _extends({}, DefaultDraftInlineStyle, customStyleMap), + customStyleFn: customStyleFn, + editorKey: this._editorKey, + editorState: editorState, + key: 'contents' + this.state.contentsKey, + textDirectionality: textDirectionality + }; + + return React.createElement( + 'div', + { className: rootClass }, + this._renderPlaceholder(), + React.createElement( + 'div', + { + className: cx('DraftEditor/editorContainer'), + ref: function ref(_ref3) { + return _this3.editorContainer = _ref3; + } }, + React.createElement( + 'div', + { + 'aria-activedescendant': readOnly ? null : this.props.ariaActiveDescendantID, + 'aria-autocomplete': readOnly ? null : this.props.ariaAutoComplete, + 'aria-controls': readOnly ? null : this.props.ariaControls, + 'aria-describedby': this.props.ariaDescribedBy || this._placeholderAccessibilityID, + 'aria-expanded': readOnly ? null : ariaExpanded, + 'aria-label': this.props.ariaLabel, + 'aria-labelledby': this.props.ariaLabelledBy, + 'aria-multiline': this.props.ariaMultiline, + autoCapitalize: this.props.autoCapitalize, + autoComplete: this.props.autoComplete, + autoCorrect: this.props.autoCorrect, + className: cx({ + // Chrome's built-in translation feature mutates the DOM in ways + // that Draft doesn't expect (ex: adding tags inside + // DraftEditorLeaf spans) and causes problems. We add notranslate + // here which makes its autotranslation skip over this subtree. + notranslate: !readOnly, + 'public/DraftEditor/content': true + }), + contentEditable: !readOnly, + 'data-testid': this.props.webDriverTestID, + onBeforeInput: this._onBeforeInput, + onBlur: this._onBlur, + onCompositionEnd: this._onCompositionEnd, + onCompositionStart: this._onCompositionStart, + onCopy: this._onCopy, + onCut: this._onCut, + onDragEnd: this._onDragEnd, + onDragEnter: this.onDragEnter, + onDragLeave: this.onDragLeave, + onDragOver: this._onDragOver, + onDragStart: this._onDragStart, + onDrop: this._onDrop, + onFocus: this._onFocus, + onInput: this._onInput, + onKeyDown: this._onKeyDown, + onKeyPress: this._onKeyPress, + onKeyUp: this._onKeyUp, + onMouseUp: this._onMouseUp, + onPaste: this._onPaste, + onSelect: this._onSelect, + ref: function ref(_ref2) { + return _this3.editor = _ref2; + }, + role: readOnly ? null : ariaRole, + spellCheck: allowSpellCheck && this.props.spellCheck, + style: contentStyle, + suppressContentEditableWarning: true, + tabIndex: this.props.tabIndex }, + React.createElement(DraftEditorContents, editorContentsProps) + ) + ) + ); + }; + + DraftEditor.prototype.componentDidMount = function componentDidMount() { + this.setMode('edit'); + + /** + * IE has a hardcoded "feature" that attempts to convert link text into + * anchors in contentEditable DOM. This breaks the editor's expectations of + * the DOM, and control is lost. Disable it to make IE behave. + * See: http://blogs.msdn.com/b/ieinternals/archive/2010/09/15/ + * ie9-beta-minor-change-list.aspx + */ + if (isIE) { + document.execCommand('AutoUrlDetect', false, false); + } + }; + + /** + * Prevent selection events from affecting the current editor state. This + * is mostly intended to defend against IE, which fires off `selectionchange` + * events regardless of whether the selection is set via the browser or + * programmatically. We only care about selection events that occur because + * of browser interaction, not re-renders and forced selections. + */ + + + DraftEditor.prototype.componentWillUpdate = function componentWillUpdate(nextProps) { + this._blockSelectEvents = true; + this._latestEditorState = nextProps.editorState; + }; + + DraftEditor.prototype.componentDidUpdate = function componentDidUpdate() { + this._blockSelectEvents = false; + this._latestCommittedEditorState = this.props.editorState; + }; + + /** + * Used via `this.focus()`. + * + * Force focus back onto the editor node. + * + * We attempt to preserve scroll position when focusing. You can also pass + * a specified scroll position (for cases like `cut` behavior where it should + * be restored to a known position). + */ + + + /** + * Used via `this.setMode(...)`. + * + * Set the behavior mode for the editor component. This switches the current + * handler module to ensure that DOM events are managed appropriately for + * the active mode. + */ + + + /** + * Used via `this.restoreEditorDOM()`. + * + * Force a complete re-render of the DraftEditorContents based on the current + * EditorState. This is useful when we know we are going to lose control of + * the DOM state (cut command, IME) and we want to make sure that + * reconciliation occurs on a version of the DOM that is synchronized with + * our EditorState. + */ + + + /** + * Used via `this.setClipboard(...)`. + * + * Set the clipboard state for a cut/copy event. + */ + + + /** + * Used via `this.getClipboard()`. + * + * Retrieve the clipboard state for a cut/copy event. + */ + + + /** + * Used via `this.update(...)`. + * + * Propagate a new `EditorState` object to higher-level components. This is + * the method by which event handlers inform the `DraftEditor` component of + * state changes. A component that composes a `DraftEditor` **must** provide + * an `onChange` prop to receive state updates passed along from this + * function. + */ + + + /** + * Used in conjunction with `onDragLeave()`, by counting the number of times + * a dragged element enters and leaves the editor (or any of its children), + * to determine when the dragged element absolutely leaves the editor. + */ + + + /** + * See `onDragEnter()`. + */ + + + return DraftEditor; +}(React.Component); + +DraftEditor.defaultProps = { + blockRenderMap: DefaultDraftBlockRenderMap, + blockRendererFn: emptyFunction.thatReturnsNull, + blockStyleFn: emptyFunction.thatReturns(''), + keyBindingFn: getDefaultKeyBinding, + readOnly: false, + spellCheck: false, + stripPastedStyles: false +}; + + +module.exports = DraftEditor; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 102 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEditorCompositionHandler + * @format + * + */ + + + +var DraftFeatureFlags = __webpack_require__(14); +var DraftModifier = __webpack_require__(6); +var EditorState = __webpack_require__(3); +var Keys = __webpack_require__(36); + +var getEntityKeyForSelection = __webpack_require__(33); +var isEventHandled = __webpack_require__(22); +var isSelectionAtLeafStart = __webpack_require__(68); + +/** + * Millisecond delay to allow `compositionstart` to fire again upon + * `compositionend`. + * + * This is used for Korean input to ensure that typing can continue without + * the editor trying to render too quickly. More specifically, Safari 7.1+ + * triggers `compositionstart` a little slower than Chrome/FF, which + * leads to composed characters being resolved and re-render occurring + * sooner than we want. + */ +var RESOLVE_DELAY = 20; + +/** + * A handful of variables used to track the current composition and its + * resolution status. These exist at the module level because it is not + * possible to have compositions occurring in multiple editors simultaneously, + * and it simplifies state management with respect to the DraftEditor component. + */ +var resolved = false; +var stillComposing = false; +var textInputData = ''; + +var DraftEditorCompositionHandler = { + onBeforeInput: function onBeforeInput(editor, e) { + textInputData = (textInputData || '') + e.data; + }, + + /** + * A `compositionstart` event has fired while we're still in composition + * mode. Continue the current composition session to prevent a re-render. + */ + onCompositionStart: function onCompositionStart(editor) { + stillComposing = true; + }, + + /** + * Attempt to end the current composition session. + * + * Defer handling because browser will still insert the chars into active + * element after `compositionend`. If a `compositionstart` event fires + * before `resolveComposition` executes, our composition session will + * continue. + * + * The `resolved` flag is useful because certain IME interfaces fire the + * `compositionend` event multiple times, thus queueing up multiple attempts + * at handling the composition. Since handling the same composition event + * twice could break the DOM, we only use the first event. Example: Arabic + * Google Input Tools on Windows 8.1 fires `compositionend` three times. + */ + onCompositionEnd: function onCompositionEnd(editor) { + resolved = false; + stillComposing = false; + setTimeout(function () { + if (!resolved) { + DraftEditorCompositionHandler.resolveComposition(editor); + } + }, RESOLVE_DELAY); + }, + + /** + * In Safari, keydown events may fire when committing compositions. If + * the arrow keys are used to commit, prevent default so that the cursor + * doesn't move, otherwise it will jump back noticeably on re-render. + */ + onKeyDown: function onKeyDown(editor, e) { + if (!stillComposing) { + // If a keydown event is received after compositionend but before the + // 20ms timer expires (ex: type option-E then backspace, or type A then + // backspace in 2-Set Korean), we should immediately resolve the + // composition and reinterpret the key press in edit mode. + DraftEditorCompositionHandler.resolveComposition(editor); + editor._onKeyDown(e); + return; + } + if (e.which === Keys.RIGHT || e.which === Keys.LEFT) { + e.preventDefault(); + } + }, + + /** + * Keypress events may fire when committing compositions. In Firefox, + * pressing RETURN commits the composition and inserts extra newline + * characters that we do not want. `preventDefault` allows the composition + * to be committed while preventing the extra characters. + */ + onKeyPress: function onKeyPress(editor, e) { + if (e.which === Keys.RETURN) { + e.preventDefault(); + } + }, + + /** + * Attempt to insert composed characters into the document. + * + * If we are still in a composition session, do nothing. Otherwise, insert + * the characters into the document and terminate the composition session. + * + * If no characters were composed -- for instance, the user + * deleted all composed characters and committed nothing new -- + * force a re-render. We also re-render when the composition occurs + * at the beginning of a leaf, to ensure that if the browser has + * created a new text node for the composition, we will discard it. + * + * Resetting innerHTML will move focus to the beginning of the editor, + * so we update to force it back to the correct place. + */ + resolveComposition: function resolveComposition(editor) { + if (stillComposing) { + return; + } + + resolved = true; + var composedChars = textInputData; + textInputData = ''; + + var editorState = EditorState.set(editor._latestEditorState, { + inCompositionMode: false + }); + + var currentStyle = editorState.getCurrentInlineStyle(); + var entityKey = getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection()); + + var mustReset = !composedChars || isSelectionAtLeafStart(editorState) || currentStyle.size > 0 || entityKey !== null; + + if (mustReset) { + editor.restoreEditorDOM(); + } + + editor.exitCurrentMode(); + + if (composedChars) { + if (DraftFeatureFlags.draft_handlebeforeinput_composed_text && editor.props.handleBeforeInput && isEventHandled(editor.props.handleBeforeInput(composedChars, editorState))) { + return; + } + // If characters have been composed, re-rendering with the update + // is sufficient to reset the editor. + var contentState = DraftModifier.replaceText(editorState.getCurrentContent(), editorState.getSelection(), composedChars, currentStyle, entityKey); + editor.update(EditorState.push(editorState, contentState, 'insert-characters')); + return; + } + + if (mustReset) { + editor.update(EditorState.set(editorState, { + nativelyRenderedContent: null, + forceSelection: true + })); + } + } +}; + +module.exports = DraftEditorCompositionHandler; + +/***/ }), +/* 103 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEditorContents-core.react + * @format + * + */ + + + +var _assign = __webpack_require__(5); + +var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DraftEditorBlock = __webpack_require__(52); +var DraftOffsetKey = __webpack_require__(26); +var EditorState = __webpack_require__(3); +var React = __webpack_require__(4); + +var cx = __webpack_require__(19); +var joinClasses = __webpack_require__(180); +var nullthrows = __webpack_require__(10); + +/** + * Provide default styling for list items. This way, lists will be styled with + * proper counters and indentation even if the caller does not specify + * their own styling at all. If more than five levels of nesting are needed, + * the necessary CSS classes can be provided via `blockStyleFn` configuration. + */ +var getListItemClasses = function getListItemClasses(type, depth, shouldResetCount, direction) { + return cx({ + 'public/DraftStyleDefault/unorderedListItem': type === 'unordered-list-item', + 'public/DraftStyleDefault/orderedListItem': type === 'ordered-list-item', + 'public/DraftStyleDefault/reset': shouldResetCount, + 'public/DraftStyleDefault/depth0': depth === 0, + 'public/DraftStyleDefault/depth1': depth === 1, + 'public/DraftStyleDefault/depth2': depth === 2, + 'public/DraftStyleDefault/depth3': depth === 3, + 'public/DraftStyleDefault/depth4': depth === 4, + 'public/DraftStyleDefault/listLTR': direction === 'LTR', + 'public/DraftStyleDefault/listRTL': direction === 'RTL' + }); +}; + +/** + * `DraftEditorContents` is the container component for all block components + * rendered for a `DraftEditor`. It is optimized to aggressively avoid + * re-rendering blocks whenever possible. + * + * This component is separate from `DraftEditor` because certain props + * (for instance, ARIA props) must be allowed to update without affecting + * the contents of the editor. + */ + +var DraftEditorContents = function (_React$Component) { + _inherits(DraftEditorContents, _React$Component); + + function DraftEditorContents() { + _classCallCheck(this, DraftEditorContents); + + return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); + } + + DraftEditorContents.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { + var prevEditorState = this.props.editorState; + var nextEditorState = nextProps.editorState; + + var prevDirectionMap = prevEditorState.getDirectionMap(); + var nextDirectionMap = nextEditorState.getDirectionMap(); + + // Text direction has changed for one or more blocks. We must re-render. + if (prevDirectionMap !== nextDirectionMap) { + return true; + } + + var didHaveFocus = prevEditorState.getSelection().getHasFocus(); + var nowHasFocus = nextEditorState.getSelection().getHasFocus(); + + if (didHaveFocus !== nowHasFocus) { + return true; + } + + var nextNativeContent = nextEditorState.getNativelyRenderedContent(); + + var wasComposing = prevEditorState.isInCompositionMode(); + var nowComposing = nextEditorState.isInCompositionMode(); + + // If the state is unchanged or we're currently rendering a natively + // rendered state, there's nothing new to be done. + if (prevEditorState === nextEditorState || nextNativeContent !== null && nextEditorState.getCurrentContent() === nextNativeContent || wasComposing && nowComposing) { + return false; + } + + var prevContent = prevEditorState.getCurrentContent(); + var nextContent = nextEditorState.getCurrentContent(); + var prevDecorator = prevEditorState.getDecorator(); + var nextDecorator = nextEditorState.getDecorator(); + return wasComposing !== nowComposing || prevContent !== nextContent || prevDecorator !== nextDecorator || nextEditorState.mustForceSelection(); + }; + + DraftEditorContents.prototype.render = function render() { + var _props = this.props, + blockRenderMap = _props.blockRenderMap, + blockRendererFn = _props.blockRendererFn, + blockStyleFn = _props.blockStyleFn, + customStyleMap = _props.customStyleMap, + customStyleFn = _props.customStyleFn, + editorState = _props.editorState, + editorKey = _props.editorKey, + textDirectionality = _props.textDirectionality; + + + var content = editorState.getCurrentContent(); + var selection = editorState.getSelection(); + var forceSelection = editorState.mustForceSelection(); + var decorator = editorState.getDecorator(); + var directionMap = nullthrows(editorState.getDirectionMap()); + + var blocksAsArray = content.getBlocksAsArray(); + var processedBlocks = []; + + var currentDepth = null; + var lastWrapperTemplate = null; + + for (var ii = 0; ii < blocksAsArray.length; ii++) { + var _block = blocksAsArray[ii]; + var key = _block.getKey(); + var blockType = _block.getType(); + + var customRenderer = blockRendererFn(_block); + var CustomComponent = void 0, + customProps = void 0, + customEditable = void 0; + if (customRenderer) { + CustomComponent = customRenderer.component; + customProps = customRenderer.props; + customEditable = customRenderer.editable; + } + + var direction = textDirectionality ? textDirectionality : directionMap.get(key); + var offsetKey = DraftOffsetKey.encode(key, 0, 0); + var componentProps = { + contentState: content, + block: _block, + blockProps: customProps, + blockStyleFn: blockStyleFn, + customStyleMap: customStyleMap, + customStyleFn: customStyleFn, + decorator: decorator, + direction: direction, + forceSelection: forceSelection, + key: key, + offsetKey: offsetKey, + selection: selection, + tree: editorState.getBlockTree(key) + }; + + var configForType = blockRenderMap.get(blockType) || blockRenderMap.get('unstyled'); + var wrapperTemplate = configForType.wrapper; + + var Element = configForType.element || blockRenderMap.get('unstyled').element; + + var depth = _block.getDepth(); + var className = ''; + if (blockStyleFn) { + className = blockStyleFn(_block); + } + + // List items are special snowflakes, since we handle nesting and + // counters manually. + if (Element === 'li') { + var shouldResetCount = lastWrapperTemplate !== wrapperTemplate || currentDepth === null || depth > currentDepth; + className = joinClasses(className, getListItemClasses(blockType, depth, shouldResetCount, direction)); + } + + var Component = CustomComponent || DraftEditorBlock; + var childProps = { + className: className, + 'data-block': true, + 'data-editor': editorKey, + 'data-offset-key': offsetKey, + key: key + }; + if (customEditable !== undefined) { + childProps = _extends({}, childProps, { + contentEditable: customEditable, + suppressContentEditableWarning: true + }); + } + + var child = React.createElement(Element, childProps, React.createElement(Component, componentProps)); + + processedBlocks.push({ + block: child, + wrapperTemplate: wrapperTemplate, + key: key, + offsetKey: offsetKey + }); + + if (wrapperTemplate) { + currentDepth = _block.getDepth(); + } else { + currentDepth = null; + } + lastWrapperTemplate = wrapperTemplate; + } + + // Group contiguous runs of blocks that have the same wrapperTemplate + var outputBlocks = []; + for (var _ii = 0; _ii < processedBlocks.length;) { + var info = processedBlocks[_ii]; + if (info.wrapperTemplate) { + var blocks = []; + do { + blocks.push(processedBlocks[_ii].block); + _ii++; + } while (_ii < processedBlocks.length && processedBlocks[_ii].wrapperTemplate === info.wrapperTemplate); + var wrapperElement = React.cloneElement(info.wrapperTemplate, { + key: info.key + '-wrap', + 'data-offset-key': info.offsetKey + }, blocks); + outputBlocks.push(wrapperElement); + } else { + outputBlocks.push(info.block); + _ii++; + } + } + + return React.createElement( + 'div', + { 'data-contents': 'true' }, + outputBlocks + ); + }; + + return DraftEditorContents; +}(React.Component); + +module.exports = DraftEditorContents; + +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEditorContents.react + * @format + * + */ + + + +var DraftEditorContents = __webpack_require__(103); + +module.exports = DraftEditorContents; + +/***/ }), +/* 105 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEditorDragHandler + * @format + * + */ + + + +var DataTransfer = __webpack_require__(72); +var DraftModifier = __webpack_require__(6); +var EditorState = __webpack_require__(3); + +var findAncestorOffsetKey = __webpack_require__(32); +var getTextContentFromFiles = __webpack_require__(65); +var getUpdatedSelectionState = __webpack_require__(66); +var isEventHandled = __webpack_require__(22); +var nullthrows = __webpack_require__(10); + +/** + * Get a SelectionState for the supplied mouse event. + */ +function getSelectionForEvent(event, editorState) { + var node = null; + var offset = null; + + if (typeof document.caretRangeFromPoint === 'function') { + var dropRange = document.caretRangeFromPoint(event.x, event.y); + node = dropRange.startContainer; + offset = dropRange.startOffset; + } else if (event.rangeParent) { + node = event.rangeParent; + offset = event.rangeOffset; + } else { + return null; + } + + node = nullthrows(node); + offset = nullthrows(offset); + var offsetKey = nullthrows(findAncestorOffsetKey(node)); + + return getUpdatedSelectionState(editorState, offsetKey, offset, offsetKey, offset); +} + +var DraftEditorDragHandler = { + /** + * Drag originating from input terminated. + */ + onDragEnd: function onDragEnd(editor) { + editor.exitCurrentMode(); + }, + + /** + * Handle data being dropped. + */ + onDrop: function onDrop(editor, e) { + var data = new DataTransfer(e.nativeEvent.dataTransfer); + + var editorState = editor._latestEditorState; + var dropSelection = getSelectionForEvent(e.nativeEvent, editorState); + + e.preventDefault(); + editor.exitCurrentMode(); + + if (dropSelection == null) { + return; + } + + var files = data.getFiles(); + if (files.length > 0) { + if (editor.props.handleDroppedFiles && isEventHandled(editor.props.handleDroppedFiles(dropSelection, files))) { + return; + } + + getTextContentFromFiles(files, function (fileText) { + fileText && editor.update(insertTextAtSelection(editorState, dropSelection, fileText)); + }); + return; + } + + var dragType = editor._internalDrag ? 'internal' : 'external'; + if (editor.props.handleDrop && isEventHandled(editor.props.handleDrop(dropSelection, data, dragType))) { + return; + } + + if (editor._internalDrag) { + editor.update(moveText(editorState, dropSelection)); + return; + } + + editor.update(insertTextAtSelection(editorState, dropSelection, data.getText())); + } +}; + +function moveText(editorState, targetSelection) { + var newContentState = DraftModifier.moveText(editorState.getCurrentContent(), editorState.getSelection(), targetSelection); + return EditorState.push(editorState, newContentState, 'insert-fragment'); +} + +/** + * Insert text at a specified selection. + */ +function insertTextAtSelection(editorState, selection, text) { + var newContentState = DraftModifier.insertText(editorState.getCurrentContent(), selection, text, editorState.getCurrentInlineStyle()); + return EditorState.push(editorState, newContentState, 'insert-fragment'); +} + +module.exports = DraftEditorDragHandler; + +/***/ }), +/* 106 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEditorEditHandler + * @format + * + */ + + + +var onBeforeInput = __webpack_require__(125); +var onBlur = __webpack_require__(126); +var onCompositionStart = __webpack_require__(127); +var onCopy = __webpack_require__(128); +var onCut = __webpack_require__(129); +var onDragOver = __webpack_require__(130); +var onDragStart = __webpack_require__(131); +var onFocus = __webpack_require__(132); +var onInput = __webpack_require__(133); +var onKeyDown = __webpack_require__(134); +var onPaste = __webpack_require__(135); +var onSelect = __webpack_require__(136); + +var DraftEditorEditHandler = { + onBeforeInput: onBeforeInput, + onBlur: onBlur, + onCompositionStart: onCompositionStart, + onCopy: onCopy, + onCut: onCut, + onDragOver: onDragOver, + onDragStart: onDragStart, + onFocus: onFocus, + onInput: onInput, + onKeyDown: onKeyDown, + onPaste: onPaste, + onSelect: onSelect +}; + +module.exports = DraftEditorEditHandler; + +/***/ }), +/* 107 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEditorLeaf.react + * @format + * + */ + + + +var _assign = __webpack_require__(5); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DraftEditorTextNode = __webpack_require__(109); +var React = __webpack_require__(4); +var ReactDOM = __webpack_require__(17); + +var invariant = __webpack_require__(2); +var setDraftEditorSelection = __webpack_require__(160); + +/** + * All leaf nodes in the editor are spans with single text nodes. Leaf + * elements are styled based on the merging of an optional custom style map + * and a default style map. + * + * `DraftEditorLeaf` also provides a wrapper for calling into the imperative + * DOM Selection API. In this way, top-level components can declaratively + * maintain the selection state. + */ +var DraftEditorLeaf = function (_React$Component) { + _inherits(DraftEditorLeaf, _React$Component); + + function DraftEditorLeaf() { + _classCallCheck(this, DraftEditorLeaf); + + return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); + } + + DraftEditorLeaf.prototype._setSelection = function _setSelection() { + var selection = this.props.selection; + + // If selection state is irrelevant to the parent block, no-op. + + if (selection == null || !selection.getHasFocus()) { + return; + } + + var _props = this.props, + block = _props.block, + start = _props.start, + text = _props.text; + + var blockKey = block.getKey(); + var end = start + text.length; + if (!selection.hasEdgeWithin(blockKey, start, end)) { + return; + } + + // Determine the appropriate target node for selection. If the child + // is not a text node, it is a
spacer. In this case, use the + // itself as the selection target. + var node = ReactDOM.findDOMNode(this); + !node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing node') : invariant(false) : void 0; + var child = node.firstChild; + !child ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing child') : invariant(false) : void 0; + var targetNode = void 0; + + if (child.nodeType === Node.TEXT_NODE) { + targetNode = child; + } else if (child.tagName === 'BR') { + targetNode = node; + } else { + targetNode = child.firstChild; + !targetNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing targetNode') : invariant(false) : void 0; + } + + setDraftEditorSelection(selection, targetNode, blockKey, start, end); + }; + /** + * By making individual leaf instances aware of their context within + * the text of the editor, we can set our selection range more + * easily than we could in the non-React world. + * + * Note that this depends on our maintaining tight control over the + * DOM structure of the DraftEditor component. If leaves had multiple + * text nodes, this would be harder. + */ + + DraftEditorLeaf.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { + var leafNode = ReactDOM.findDOMNode(this.leaf); + !leafNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing leafNode') : invariant(false) : void 0; + return leafNode.textContent !== nextProps.text || nextProps.styleSet !== this.props.styleSet || nextProps.forceSelection; + }; + + DraftEditorLeaf.prototype.componentDidUpdate = function componentDidUpdate() { + this._setSelection(); + }; + + DraftEditorLeaf.prototype.componentDidMount = function componentDidMount() { + this._setSelection(); + }; + + DraftEditorLeaf.prototype.render = function render() { + var _this2 = this; + + var block = this.props.block; + var text = this.props.text; + + // If the leaf is at the end of its block and ends in a soft newline, append + // an extra line feed character. Browsers collapse trailing newline + // characters, which leaves the cursor in the wrong place after a + // shift+enter. The extra character repairs this. + + if (text.endsWith('\n') && this.props.isLast) { + text += '\n'; + } + + var _props2 = this.props, + customStyleMap = _props2.customStyleMap, + customStyleFn = _props2.customStyleFn, + offsetKey = _props2.offsetKey, + styleSet = _props2.styleSet; + + var styleObj = styleSet.reduce(function (map, styleName) { + var mergedStyles = {}; + var style = customStyleMap[styleName]; + + if (style !== undefined && map.textDecoration !== style.textDecoration) { + // .trim() is necessary for IE9/10/11 and Edge + mergedStyles.textDecoration = [map.textDecoration, style.textDecoration].join(' ').trim(); + } + + return _assign(map, style, mergedStyles); + }, {}); + + if (customStyleFn) { + var newStyles = customStyleFn(styleSet, block); + styleObj = _assign(styleObj, newStyles); + } + + return React.createElement( + 'span', + { + 'data-offset-key': offsetKey, + ref: function ref(_ref) { + return _this2.leaf = _ref; + }, + style: styleObj }, + React.createElement( + DraftEditorTextNode, + null, + text + ) + ); + }; + + return DraftEditorLeaf; +}(React.Component); + +module.exports = DraftEditorLeaf; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 108 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEditorPlaceholder.react + * @format + * + */ + + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var React = __webpack_require__(4); + +var cx = __webpack_require__(19); + +/** + * This component is responsible for rendering placeholder text for the + * `DraftEditor` component. + * + * Override placeholder style via CSS. + */ +var DraftEditorPlaceholder = function (_React$Component) { + _inherits(DraftEditorPlaceholder, _React$Component); + + function DraftEditorPlaceholder() { + _classCallCheck(this, DraftEditorPlaceholder); + + return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); + } + + DraftEditorPlaceholder.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { + return this.props.text !== nextProps.text || this.props.editorState.getSelection().getHasFocus() !== nextProps.editorState.getSelection().getHasFocus(); + }; + + DraftEditorPlaceholder.prototype.render = function render() { + var hasFocus = this.props.editorState.getSelection().getHasFocus(); + + var className = cx({ + 'public/DraftEditorPlaceholder/root': true, + 'public/DraftEditorPlaceholder/hasFocus': hasFocus + }); + + var contentStyle = { + whiteSpace: 'pre-wrap' + }; + + return React.createElement( + 'div', + { className: className }, + React.createElement( + 'div', + { + className: cx('public/DraftEditorPlaceholder/inner'), + id: this.props.accessibilityID, + style: contentStyle }, + this.props.text + ) + ); + }; + + return DraftEditorPlaceholder; +}(React.Component); + +module.exports = DraftEditorPlaceholder; + +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEditorTextNode.react + * @format + * + */ + + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var React = __webpack_require__(4); +var ReactDOM = __webpack_require__(17); +var UserAgent = __webpack_require__(12); + +var invariant = __webpack_require__(2); + +// In IE, spans with
tags render as two newlines. By rendering a span +// with only a newline character, we can be sure to render a single line. +var useNewlineChar = UserAgent.isBrowser('IE <= 11'); + +/** + * Check whether the node should be considered a newline. + */ +function isNewline(node) { + return useNewlineChar ? node.textContent === '\n' : node.tagName === 'BR'; +} + +/** + * Placeholder elements for empty text content. + * + * What is this `data-text` attribute, anyway? It turns out that we need to + * put an attribute on the lowest-level text node in order to preserve correct + * spellcheck handling. If the is naked, Chrome and Safari may do + * bizarre things to do the DOM -- split text nodes, create extra spans, etc. + * If the has an attribute, this appears not to happen. + * See http://jsfiddle.net/9khdavod/ for the failure case, and + * http://jsfiddle.net/7pg143f7/ for the fixed case. + */ +var NEWLINE_A = useNewlineChar ? React.createElement( + 'span', + { key: 'A', 'data-text': 'true' }, + '\n' +) : React.createElement('br', { key: 'A', 'data-text': 'true' }); + +var NEWLINE_B = useNewlineChar ? React.createElement( + 'span', + { key: 'B', 'data-text': 'true' }, + '\n' +) : React.createElement('br', { key: 'B', 'data-text': 'true' }); + +/** + * The lowest-level component in a `DraftEditor`, the text node component + * replaces the default React text node implementation. This allows us to + * perform custom handling of newline behavior and avoid re-rendering text + * nodes with DOM state that already matches the expectations of our immutable + * editor state. + */ +var DraftEditorTextNode = function (_React$Component) { + _inherits(DraftEditorTextNode, _React$Component); + + function DraftEditorTextNode(props) { + _classCallCheck(this, DraftEditorTextNode); + + // By flipping this flag, we also keep flipping keys which forces + // React to remount this node every time it rerenders. + var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); + + _this._forceFlag = false; + return _this; + } + + DraftEditorTextNode.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { + var node = ReactDOM.findDOMNode(this); + var shouldBeNewline = nextProps.children === ''; + !(node instanceof Element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'node is not an Element') : invariant(false) : void 0; + if (shouldBeNewline) { + return !isNewline(node); + } + return node.textContent !== nextProps.children; + }; + + DraftEditorTextNode.prototype.componentDidMount = function componentDidMount() { + this._forceFlag = !this._forceFlag; + }; + + DraftEditorTextNode.prototype.componentDidUpdate = function componentDidUpdate() { + this._forceFlag = !this._forceFlag; + }; + + DraftEditorTextNode.prototype.render = function render() { + if (this.props.children === '') { + return this._forceFlag ? NEWLINE_A : NEWLINE_B; + } + return React.createElement( + 'span', + { key: this._forceFlag ? 'A' : 'B', 'data-text': 'true' }, + this.props.children + ); + }; + + return DraftEditorTextNode; +}(React.Component); + +module.exports = DraftEditorTextNode; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftEntitySegments + * @format + * + */ + + + +/** + * Identify the range to delete from a segmented entity. + * + * Rules: + * + * Example: 'John F. Kennedy' + * + * - Deletion from within any non-whitespace (i.e. ['John', 'F.', 'Kennedy']) + * will return the range of that text. + * + * 'John F. Kennedy' -> 'John F.' + * ^ + * + * - Forward deletion of whitespace will remove the following section: + * + * 'John F. Kennedy' -> 'John Kennedy' + * ^ + * + * - Backward deletion of whitespace will remove the previous section: + * + * 'John F. Kennedy' -> 'F. Kennedy' + * ^ + */ +var DraftEntitySegments = { + getRemovalRange: function getRemovalRange(selectionStart, selectionEnd, text, entityStart, direction) { + var segments = text.split(' '); + segments = segments.map(function ( /*string*/segment, /*number*/ii) { + if (direction === 'forward') { + if (ii > 0) { + return ' ' + segment; + } + } else if (ii < segments.length - 1) { + return segment + ' '; + } + return segment; + }); + + var segmentStart = entityStart; + var segmentEnd; + var segment; + var removalStart = null; + var removalEnd = null; + + for (var jj = 0; jj < segments.length; jj++) { + segment = segments[jj]; + segmentEnd = segmentStart + segment.length; + + // Our selection overlaps this segment. + if (selectionStart < segmentEnd && segmentStart < selectionEnd) { + if (removalStart !== null) { + removalEnd = segmentEnd; + } else { + removalStart = segmentStart; + removalEnd = segmentEnd; + } + } else if (removalStart !== null) { + break; + } + + segmentStart = segmentEnd; + } + + var entityEnd = entityStart + text.length; + var atStart = removalStart === entityStart; + var atEnd = removalEnd === entityEnd; + + if (!atStart && atEnd || atStart && !atEnd) { + if (direction === 'forward') { + if (removalEnd !== entityEnd) { + removalEnd++; + } + } else if (removalStart !== entityStart) { + removalStart--; + } + } + + return { + start: removalStart, + end: removalEnd + }; + } +}; + +module.exports = DraftEntitySegments; + +/***/ }), +/* 111 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftFeatureFlags-core + * @format + * + */ + + + +var DraftFeatureFlags = { + draft_killswitch_allow_nontextnodes: false, + draft_segmented_entities_behavior: false, + draft_handlebeforeinput_composed_text: false, + draft_tree_data_support: false +}; + +module.exports = DraftFeatureFlags; + +/***/ }), +/* 112 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftJsDebugLogging + */ + + + +module.exports = { + logSelectionStateFailure: function logSelectionStateFailure() { + return null; + } +}; + +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftPasteProcessor + * @format + * + */ + + + +var _assign = __webpack_require__(5); + +var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var CharacterMetadata = __webpack_require__(7); +var ContentBlock = __webpack_require__(15); +var ContentBlockNode = __webpack_require__(9); +var DraftFeatureFlags = __webpack_require__(14); +var Immutable = __webpack_require__(1); + +var convertFromHTMLtoContentBlocks = __webpack_require__(57); +var generateRandomKey = __webpack_require__(13); +var getSafeBodyFromHTML = __webpack_require__(63); +var sanitizeDraftText = __webpack_require__(35); + +var List = Immutable.List, + Repeat = Immutable.Repeat; + + +var experimentalTreeDataSupport = DraftFeatureFlags.draft_tree_data_support; +var ContentBlockRecord = experimentalTreeDataSupport ? ContentBlockNode : ContentBlock; + +var DraftPasteProcessor = { + processHTML: function processHTML(html, blockRenderMap) { + return convertFromHTMLtoContentBlocks(html, getSafeBodyFromHTML, blockRenderMap); + }, + processText: function processText(textBlocks, character, type) { + return textBlocks.reduce(function (acc, textLine, index) { + textLine = sanitizeDraftText(textLine); + var key = generateRandomKey(); + + var blockNodeConfig = { + key: key, + type: type, + text: textLine, + characterList: List(Repeat(character, textLine.length)) + }; + + // next block updates previous block + if (experimentalTreeDataSupport && index !== 0) { + var prevSiblingIndex = index - 1; + // update previous block + var previousBlock = acc[prevSiblingIndex] = acc[prevSiblingIndex].merge({ + nextSibling: key + }); + blockNodeConfig = _extends({}, blockNodeConfig, { + prevSibling: previousBlock.getKey() + }); + } + + acc.push(new ContentBlockRecord(blockNodeConfig)); + + return acc; + }, []); + } +}; + +module.exports = DraftPasteProcessor; + +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) { + +var _assign = __webpack_require__(5); + +var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule DraftTreeAdapter + * @format + * + * + * This is unstable and not part of the public API and should not be used by + * production systems. This file may be update/removed without notice. + */ + +var invariant = __webpack_require__(2); + +var traverseInDepthOrder = function traverseInDepthOrder(blocks, fn) { + var stack = [].concat(blocks).reverse(); + while (stack.length) { + var _block = stack.pop(); + + fn(_block); + + var children = _block.children; + + !Array.isArray(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tree raw block') : invariant(false) : void 0; + + stack = stack.concat([].concat(children.reverse())); + } +}; + +var isListBlock = function isListBlock(block) { + if (!(block && block.type)) { + return false; + } + var type = block.type; + + return type === 'unordered-list-item' || type === 'ordered-list-item'; +}; + +var addDepthToChildren = function addDepthToChildren(block) { + if (Array.isArray(block.children)) { + block.children = block.children.map(function (child) { + return child.type === block.type ? _extends({}, child, { depth: (block.depth || 0) + 1 }) : child; + }); + } +}; + +/** + * This adapter is intended to be be used as an adapter to draft tree data + * + * draft state <=====> draft tree state + */ +var DraftTreeAdapter = { + /** + * Converts from a tree raw state back to draft raw state + */ + fromRawTreeStateToRawState: function fromRawTreeStateToRawState(draftTreeState) { + var blocks = draftTreeState.blocks; + + var transformedBlocks = []; + + !Array.isArray(blocks) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid raw state') : invariant(false) : void 0; + + if (!Array.isArray(blocks) || !blocks.length) { + return draftTreeState; + } + + traverseInDepthOrder(blocks, function (block) { + var newBlock = _extends({}, block); + + if (isListBlock(block)) { + newBlock.depth = newBlock.depth || 0; + addDepthToChildren(block); + } + + delete newBlock.children; + + transformedBlocks.push(newBlock); + }); + + draftTreeState.blocks = transformedBlocks; + + return _extends({}, draftTreeState, { + blocks: transformedBlocks + }); + }, + + + /** + * Converts from draft raw state to tree draft state + */ + fromRawStateToRawTreeState: function fromRawStateToRawTreeState(draftState) { + var lastListDepthCacheRef = {}; + var transformedBlocks = []; + + draftState.blocks.forEach(function (block) { + var isList = isListBlock(block); + var depth = block.depth || 0; + var treeBlock = _extends({}, block, { + children: [] + }); + + if (!isList) { + // reset the cache path + lastListDepthCacheRef = {}; + transformedBlocks.push(treeBlock); + return; + } + + // update our depth cache reference path + lastListDepthCacheRef[depth] = treeBlock; + + // if we are greater than zero we must have seen a parent already + if (depth > 0) { + var parent = lastListDepthCacheRef[depth - 1]; + + !parent ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid depth for RawDraftContentBlock') : invariant(false) : void 0; + + // push nested list blocks + parent.children.push(treeBlock); + return; + } + + // push root list blocks + transformedBlocks.push(treeBlock); + }); + + return _extends({}, draftState, { + blocks: transformedBlocks + }); + } +}; + +module.exports = DraftTreeAdapter; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EditorBidiService + * @format + * + */ + + + +var Immutable = __webpack_require__(1); +var UnicodeBidiService = __webpack_require__(166); + +var nullthrows = __webpack_require__(10); + +var OrderedMap = Immutable.OrderedMap; + + +var bidiService; + +var EditorBidiService = { + getDirectionMap: function getDirectionMap(content, prevBidiMap) { + if (!bidiService) { + bidiService = new UnicodeBidiService(); + } else { + bidiService.reset(); + } + + var blockMap = content.getBlockMap(); + var nextBidi = blockMap.valueSeq().map(function (block) { + return nullthrows(bidiService).getDirection(block.getText()); + }); + var bidiMap = OrderedMap(blockMap.keySeq().zip(nextBidi)); + + if (prevBidiMap != null && Immutable.is(prevBidiMap, bidiMap)) { + return prevBidiMap; + } + + return bidiMap; + } +}; + +module.exports = EditorBidiService; + +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule SecondaryClipboard + * @format + * + */ + + + +var DraftModifier = __webpack_require__(6); +var EditorState = __webpack_require__(3); + +var getContentStateFragment = __webpack_require__(27); +var nullthrows = __webpack_require__(10); + +var clipboard = null; + +/** + * Some systems offer a "secondary" clipboard to allow quick internal cut + * and paste behavior. For instance, Ctrl+K (cut) and Ctrl+Y (paste). + */ +var SecondaryClipboard = { + cut: function cut(editorState) { + var content = editorState.getCurrentContent(); + var selection = editorState.getSelection(); + var targetRange = null; + + if (selection.isCollapsed()) { + var anchorKey = selection.getAnchorKey(); + var blockEnd = content.getBlockForKey(anchorKey).getLength(); + + if (blockEnd === selection.getAnchorOffset()) { + return editorState; + } + + targetRange = selection.set('focusOffset', blockEnd); + } else { + targetRange = selection; + } + + targetRange = nullthrows(targetRange); + clipboard = getContentStateFragment(content, targetRange); + + var afterRemoval = DraftModifier.removeRange(content, targetRange, 'forward'); + + if (afterRemoval === content) { + return editorState; + } + + return EditorState.push(editorState, afterRemoval, 'remove-range'); + }, + + paste: function paste(editorState) { + if (!clipboard) { + return editorState; + } + + var newContent = DraftModifier.replaceWithFragment(editorState.getCurrentContent(), editorState.getSelection(), clipboard); + + return EditorState.push(editorState, newContent, 'insert-fragment'); + } +}; + +module.exports = SecondaryClipboard; + +/***/ }), +/* 117 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule adjustBlockDepthForContentState + * @format + * + */ + + + +function adjustBlockDepthForContentState(contentState, selectionState, adjustment, maxDepth) { + var startKey = selectionState.getStartKey(); + var endKey = selectionState.getEndKey(); + var blockMap = contentState.getBlockMap(); + var blocks = blockMap.toSeq().skipUntil(function (_, k) { + return k === startKey; + }).takeUntil(function (_, k) { + return k === endKey; + }).concat([[endKey, blockMap.get(endKey)]]).map(function (block) { + var depth = block.getDepth() + adjustment; + depth = Math.max(0, Math.min(depth, maxDepth)); + return block.set('depth', depth); + }); + + blockMap = blockMap.merge(blocks); + + return contentState.merge({ + blockMap: blockMap, + selectionBefore: selectionState, + selectionAfter: selectionState + }); +} + +module.exports = adjustBlockDepthForContentState; + +/***/ }), +/* 118 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule applyEntityToContentBlock + * @format + * + */ + + + +var CharacterMetadata = __webpack_require__(7); + +function applyEntityToContentBlock(contentBlock, start, end, entityKey) { + var characterList = contentBlock.getCharacterList(); + while (start < end) { + characterList = characterList.set(start, CharacterMetadata.applyEntity(characterList.get(start), entityKey)); + start++; + } + return contentBlock.set('characterList', characterList); +} + +module.exports = applyEntityToContentBlock; + +/***/ }), +/* 119 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule applyEntityToContentState + * @format + * + */ + + + +var Immutable = __webpack_require__(1); + +var applyEntityToContentBlock = __webpack_require__(118); + +function applyEntityToContentState(contentState, selectionState, entityKey) { + var blockMap = contentState.getBlockMap(); + var startKey = selectionState.getStartKey(); + var startOffset = selectionState.getStartOffset(); + var endKey = selectionState.getEndKey(); + var endOffset = selectionState.getEndOffset(); + + var newBlocks = blockMap.skipUntil(function (_, k) { + return k === startKey; + }).takeUntil(function (_, k) { + return k === endKey; + }).toOrderedMap().merge(Immutable.OrderedMap([[endKey, blockMap.get(endKey)]])).map(function (block, blockKey) { + var sliceStart = blockKey === startKey ? startOffset : 0; + var sliceEnd = blockKey === endKey ? endOffset : block.getLength(); + return applyEntityToContentBlock(block, sliceStart, sliceEnd, entityKey); + }); + + return contentState.merge({ + blockMap: blockMap.merge(newBlocks), + selectionBefore: selectionState, + selectionAfter: selectionState + }); +} + +module.exports = applyEntityToContentState; + +/***/ }), +/* 120 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule convertFromDraftStateToRaw + * @format + * + */ + + + +var _assign = __webpack_require__(5); + +var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var ContentBlock = __webpack_require__(15); +var ContentBlockNode = __webpack_require__(9); +var DraftStringKey = __webpack_require__(55); + +var encodeEntityRanges = __webpack_require__(137); +var encodeInlineStyleRanges = __webpack_require__(138); +var invariant = __webpack_require__(2); + +var createRawBlock = function createRawBlock(block, entityStorageMap) { + return { + key: block.getKey(), + text: block.getText(), + type: block.getType(), + depth: block.getDepth(), + inlineStyleRanges: encodeInlineStyleRanges(block), + entityRanges: encodeEntityRanges(block, entityStorageMap), + data: block.getData().toObject() + }; +}; + +var insertRawBlock = function insertRawBlock(block, entityMap, rawBlocks, blockCacheRef) { + if (block instanceof ContentBlock) { + rawBlocks.push(createRawBlock(block, entityMap)); + return; + } + + !(block instanceof ContentBlockNode) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'block is not a BlockNode') : invariant(false) : void 0; + + var parentKey = block.getParentKey(); + var rawBlock = blockCacheRef[block.getKey()] = _extends({}, createRawBlock(block, entityMap), { + children: [] + }); + + if (parentKey) { + blockCacheRef[parentKey].children.push(rawBlock); + return; + } + + rawBlocks.push(rawBlock); +}; + +var encodeRawBlocks = function encodeRawBlocks(contentState, rawState) { + var entityMap = rawState.entityMap; + + + var rawBlocks = []; + + var blockCacheRef = {}; + var entityCacheRef = {}; + var entityStorageKey = 0; + + contentState.getBlockMap().forEach(function (block) { + block.findEntityRanges(function (character) { + return character.getEntity() !== null; + }, function (start) { + var entityKey = block.getEntityAt(start); + // Stringify to maintain order of otherwise numeric keys. + var stringifiedEntityKey = DraftStringKey.stringify(entityKey); + // This makes this function resilient to two entities + // erroneously having the same key + if (entityCacheRef[stringifiedEntityKey]) { + return; + } + entityCacheRef[stringifiedEntityKey] = entityKey; + // we need the `any` casting here since this is a temporary state + // where we will later on flip the entity map and populate it with + // real entity, at this stage we just need to map back the entity + // key used by the BlockNode + entityMap[stringifiedEntityKey] = '' + entityStorageKey; + entityStorageKey++; + }); + + insertRawBlock(block, entityMap, rawBlocks, blockCacheRef); + }); + + return { + blocks: rawBlocks, + entityMap: entityMap + }; +}; + +// Flip storage map so that our storage keys map to global +// DraftEntity keys. +var encodeRawEntityMap = function encodeRawEntityMap(contentState, rawState) { + var blocks = rawState.blocks, + entityMap = rawState.entityMap; + + + var rawEntityMap = {}; + + Object.keys(entityMap).forEach(function (key, index) { + var entity = contentState.getEntity(DraftStringKey.unstringify(key)); + rawEntityMap[index] = { + type: entity.getType(), + mutability: entity.getMutability(), + data: entity.getData() + }; + }); + + return { + blocks: blocks, + entityMap: rawEntityMap + }; +}; + +var convertFromDraftStateToRaw = function convertFromDraftStateToRaw(contentState) { + var rawDraftContentState = { + entityMap: {}, + blocks: [] + }; + + // add blocks + rawDraftContentState = encodeRawBlocks(contentState, rawDraftContentState); + + // add entities + rawDraftContentState = encodeRawEntityMap(contentState, rawDraftContentState); + + return rawDraftContentState; +}; + +module.exports = convertFromDraftStateToRaw; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 121 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule convertFromRawToDraftState + * @format + * + */ + + + +var _assign = __webpack_require__(5); + +var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var ContentBlock = __webpack_require__(15); +var ContentBlockNode = __webpack_require__(9); +var ContentState = __webpack_require__(29); +var DraftEntity = __webpack_require__(25); +var DraftFeatureFlags = __webpack_require__(14); +var DraftTreeAdapter = __webpack_require__(114); +var Immutable = __webpack_require__(1); +var SelectionState = __webpack_require__(18); + +var createCharacterList = __webpack_require__(122); +var decodeEntityRanges = __webpack_require__(123); +var decodeInlineStyleRanges = __webpack_require__(124); +var generateRandomKey = __webpack_require__(13); +var invariant = __webpack_require__(2); + +var experimentalTreeDataSupport = DraftFeatureFlags.draft_tree_data_support; + +var List = Immutable.List, + Map = Immutable.Map, + OrderedMap = Immutable.OrderedMap; + + +var decodeBlockNodeConfig = function decodeBlockNodeConfig(block, entityMap) { + var key = block.key, + type = block.type, + data = block.data, + text = block.text, + depth = block.depth; + + + var blockNodeConfig = { + text: text, + depth: depth || 0, + type: type || 'unstyled', + key: key || generateRandomKey(), + data: Map(data), + characterList: decodeCharacterList(block, entityMap) + }; + + return blockNodeConfig; +}; + +var decodeCharacterList = function decodeCharacterList(block, entityMap) { + var text = block.text, + rawEntityRanges = block.entityRanges, + rawInlineStyleRanges = block.inlineStyleRanges; + + + var entityRanges = rawEntityRanges || []; + var inlineStyleRanges = rawInlineStyleRanges || []; + + // Translate entity range keys to the DraftEntity map. + return createCharacterList(decodeInlineStyleRanges(text, inlineStyleRanges), decodeEntityRanges(text, entityRanges.filter(function (range) { + return entityMap.hasOwnProperty(range.key); + }).map(function (range) { + return _extends({}, range, { key: entityMap[range.key] }); + }))); +}; + +var addKeyIfMissing = function addKeyIfMissing(block) { + return _extends({}, block, { + key: block.key || generateRandomKey() + }); +}; + +/** + * Node stack is responsible to ensure we traverse the tree only once + * in depth order, while also providing parent refs to inner nodes to + * construct their links. + */ +var updateNodeStack = function updateNodeStack(stack, nodes, parentRef) { + var nodesWithParentRef = nodes.map(function (block) { + return _extends({}, block, { + parentRef: parentRef + }); + }); + + // since we pop nodes from the stack we need to insert them in reverse + return stack.concat(nodesWithParentRef.reverse()); +}; + +/** + * This will build a tree draft content state by creating the node + * reference links into a single tree walk. Each node has a link + * reference to "parent", "children", "nextSibling" and "prevSibling" + * blockMap will be created using depth ordering. + */ +var decodeContentBlockNodes = function decodeContentBlockNodes(blocks, entityMap) { + return blocks + // ensure children have valid keys to enable sibling links + .map(addKeyIfMissing).reduce(function (blockMap, block, index) { + !Array.isArray(block.children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'invalid RawDraftContentBlock can not be converted to ContentBlockNode') : invariant(false) : void 0; + + // ensure children have valid keys to enable sibling links + var children = block.children.map(addKeyIfMissing); + + // root level nodes + var contentBlockNode = new ContentBlockNode(_extends({}, decodeBlockNodeConfig(block, entityMap), { + prevSibling: index === 0 ? null : blocks[index - 1].key, + nextSibling: index === blocks.length - 1 ? null : blocks[index + 1].key, + children: List(children.map(function (child) { + return child.key; + })) + })); + + // push root node to blockMap + blockMap = blockMap.set(contentBlockNode.getKey(), contentBlockNode); + + // this stack is used to ensure we visit all nodes respecting depth ordering + var stack = updateNodeStack([], children, contentBlockNode); + + // start computing children nodes + while (stack.length > 0) { + // we pop from the stack and start processing this node + var node = stack.pop(); + + // parentRef already points to a converted ContentBlockNode + var parentRef = node.parentRef; + var siblings = parentRef.getChildKeys(); + var _index = siblings.indexOf(node.key); + var isValidBlock = Array.isArray(node.children); + + if (!isValidBlock) { + !isValidBlock ? process.env.NODE_ENV !== 'production' ? invariant(false, 'invalid RawDraftContentBlock can not be converted to ContentBlockNode') : invariant(false) : void 0; + break; + } + + // ensure children have valid keys to enable sibling links + var _children = node.children.map(addKeyIfMissing); + + var _contentBlockNode = new ContentBlockNode(_extends({}, decodeBlockNodeConfig(node, entityMap), { + parent: parentRef.getKey(), + children: List(_children.map(function (child) { + return child.key; + })), + prevSibling: _index === 0 ? null : siblings.get(_index - 1), + nextSibling: _index === siblings.size - 1 ? null : siblings.get(_index + 1) + })); + + // push node to blockMap + blockMap = blockMap.set(_contentBlockNode.getKey(), _contentBlockNode); + + // this stack is used to ensure we visit all nodes respecting depth ordering + stack = updateNodeStack(stack, _children, _contentBlockNode); + } + + return blockMap; + }, OrderedMap()); +}; + +var decodeContentBlocks = function decodeContentBlocks(blocks, entityMap) { + return OrderedMap(blocks.map(function (block) { + var contentBlock = new ContentBlock(decodeBlockNodeConfig(block, entityMap)); + return [contentBlock.getKey(), contentBlock]; + })); +}; + +var decodeRawBlocks = function decodeRawBlocks(rawState, entityMap) { + var isTreeRawBlock = Array.isArray(rawState.blocks[0].children); + var rawBlocks = experimentalTreeDataSupport && !isTreeRawBlock ? DraftTreeAdapter.fromRawStateToRawTreeState(rawState).blocks : rawState.blocks; + + if (!experimentalTreeDataSupport) { + return decodeContentBlocks(isTreeRawBlock ? DraftTreeAdapter.fromRawTreeStateToRawState(rawState).blocks : rawBlocks, entityMap); + } + + return decodeContentBlockNodes(rawBlocks, entityMap); +}; + +var decodeRawEntityMap = function decodeRawEntityMap(rawState) { + var rawEntityMap = rawState.entityMap; + + var entityMap = {}; + + // TODO: Update this once we completely remove DraftEntity + Object.keys(rawEntityMap).forEach(function (rawEntityKey) { + var _rawEntityMap$rawEnti = rawEntityMap[rawEntityKey], + type = _rawEntityMap$rawEnti.type, + mutability = _rawEntityMap$rawEnti.mutability, + data = _rawEntityMap$rawEnti.data; + + // get the key reference to created entity + + entityMap[rawEntityKey] = DraftEntity.__create(type, mutability, data || {}); + }); + + return entityMap; +}; + +var convertFromRawToDraftState = function convertFromRawToDraftState(rawState) { + !Array.isArray(rawState.blocks) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'invalid RawDraftContentState') : invariant(false) : void 0; + + // decode entities + var entityMap = decodeRawEntityMap(rawState); + + // decode blockMap + var blockMap = decodeRawBlocks(rawState, entityMap); + + // create initial selection + var selectionState = blockMap.isEmpty() ? new SelectionState() : SelectionState.createEmpty(blockMap.first().getKey()); + + return new ContentState({ + blockMap: blockMap, + entityMap: entityMap, + selectionBefore: selectionState, + selectionAfter: selectionState + }); +}; + +module.exports = convertFromRawToDraftState; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 122 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule createCharacterList + * @format + * + */ + + + +var CharacterMetadata = __webpack_require__(7); +var Immutable = __webpack_require__(1); + +var List = Immutable.List; + + +function createCharacterList(inlineStyles, entities) { + var characterArray = inlineStyles.map(function (style, ii) { + var entity = entities[ii]; + return CharacterMetadata.create({ style: style, entity: entity }); + }); + return List(characterArray); +} + +module.exports = createCharacterList; + +/***/ }), +/* 123 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule decodeEntityRanges + * @format + * + */ + + + +var UnicodeUtils = __webpack_require__(16); + +var substr = UnicodeUtils.substr; + +/** + * Convert to native JavaScript string lengths to determine ranges. + */ + +function decodeEntityRanges(text, ranges) { + var entities = Array(text.length).fill(null); + if (ranges) { + ranges.forEach(function (range) { + // Using Unicode-enabled substrings converted to JavaScript lengths, + // fill the output array with entity keys. + var start = substr(text, 0, range.offset).length; + var end = start + substr(text, range.offset, range.length).length; + for (var ii = start; ii < end; ii++) { + entities[ii] = range.key; + } + }); + } + return entities; +} + +module.exports = decodeEntityRanges; + +/***/ }), +/* 124 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule decodeInlineStyleRanges + * @format + * + */ + + + +var _require = __webpack_require__(1), + OrderedSet = _require.OrderedSet; + +var UnicodeUtils = __webpack_require__(16); + +var substr = UnicodeUtils.substr; + + +var EMPTY_SET = OrderedSet(); + +/** + * Convert to native JavaScript string lengths to determine ranges. + */ +function decodeInlineStyleRanges(text, ranges) { + var styles = Array(text.length).fill(EMPTY_SET); + if (ranges) { + ranges.forEach(function ( /*object*/range) { + var cursor = substr(text, 0, range.offset).length; + var end = cursor + substr(text, range.offset, range.length).length; + while (cursor < end) { + styles[cursor] = styles[cursor].add(range.style); + cursor++; + } + }); + } + return styles; +} + +module.exports = decodeInlineStyleRanges; + +/***/ }), +/* 125 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnBeforeInput + * @format + * + */ + + + +var BlockTree = __webpack_require__(49); +var DraftModifier = __webpack_require__(6); +var EditorState = __webpack_require__(3); +var UserAgent = __webpack_require__(12); + +var getEntityKeyForSelection = __webpack_require__(33); +var isEventHandled = __webpack_require__(22); +var isSelectionAtLeafStart = __webpack_require__(68); +var nullthrows = __webpack_require__(10); +var setImmediate = __webpack_require__(183); + +// When nothing is focused, Firefox regards two characters, `'` and `/`, as +// commands that should open and focus the "quickfind" search bar. This should +// *never* happen while a contenteditable is focused, but as of v28, it +// sometimes does, even when the keypress event target is the contenteditable. +// This breaks the input. Special case these characters to ensure that when +// they are typed, we prevent default on the event to make sure not to +// trigger quickfind. +var FF_QUICKFIND_CHAR = "'"; +var FF_QUICKFIND_LINK_CHAR = '/'; +var isFirefox = UserAgent.isBrowser('Firefox'); + +function mustPreventDefaultForCharacter(character) { + return isFirefox && (character == FF_QUICKFIND_CHAR || character == FF_QUICKFIND_LINK_CHAR); +} + +/** + * Replace the current selection with the specified text string, with the + * inline style and entity key applied to the newly inserted text. + */ +function replaceText(editorState, text, inlineStyle, entityKey) { + var contentState = DraftModifier.replaceText(editorState.getCurrentContent(), editorState.getSelection(), text, inlineStyle, entityKey); + return EditorState.push(editorState, contentState, 'insert-characters'); +} + +/** + * When `onBeforeInput` executes, the browser is attempting to insert a + * character into the editor. Apply this character data to the document, + * allowing native insertion if possible. + * + * Native insertion is encouraged in order to limit re-rendering and to + * preserve spellcheck highlighting, which disappears or flashes if re-render + * occurs on the relevant text nodes. + */ +function editOnBeforeInput(editor, e) { + if (editor._pendingStateFromBeforeInput !== undefined) { + editor.update(editor._pendingStateFromBeforeInput); + editor._pendingStateFromBeforeInput = undefined; + } + + var editorState = editor._latestEditorState; + + var chars = e.data; + + // In some cases (ex: IE ideographic space insertion) no character data + // is provided. There's nothing to do when this happens. + if (!chars) { + return; + } + + // Allow the top-level component to handle the insertion manually. This is + // useful when triggering interesting behaviors for a character insertion, + // Simple examples: replacing a raw text ':)' with a smile emoji or image + // decorator, or setting a block to be a list item after typing '- ' at the + // start of the block. + if (editor.props.handleBeforeInput && isEventHandled(editor.props.handleBeforeInput(chars, editorState))) { + e.preventDefault(); + return; + } + + // If selection is collapsed, conditionally allow native behavior. This + // reduces re-renders and preserves spellcheck highlighting. If the selection + // is not collapsed, we will re-render. + var selection = editorState.getSelection(); + var selectionStart = selection.getStartOffset(); + var selectionEnd = selection.getEndOffset(); + var anchorKey = selection.getAnchorKey(); + + if (!selection.isCollapsed()) { + e.preventDefault(); + + // If the currently selected text matches what the user is trying to + // replace it with, let's just update the `SelectionState`. If not, update + // the `ContentState` with the new text. + var currentlySelectedChars = editorState.getCurrentContent().getPlainText().slice(selectionStart, selectionEnd); + if (chars === currentlySelectedChars) { + editor.update(EditorState.forceSelection(editorState, selection.merge({ + focusOffset: selectionEnd + }))); + } else { + editor.update(replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection()))); + } + return; + } + + var newEditorState = replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection())); + + // Bunch of different cases follow where we need to prevent native insertion. + var mustPreventNative = false; + if (!mustPreventNative) { + // Browsers tend to insert text in weird places in the DOM when typing at + // the start of a leaf, so we'll handle it ourselves. + mustPreventNative = isSelectionAtLeafStart(editor._latestCommittedEditorState); + } + if (!mustPreventNative) { + // Chrome will also split up a node into two pieces if it contains a Tab + // char, for no explicable reason. Seemingly caused by this commit: + // https://chromium.googlesource.com/chromium/src/+/013ac5eaf3%5E%21/ + var nativeSelection = global.getSelection(); + // Selection is necessarily collapsed at this point due to earlier check. + if (nativeSelection.anchorNode && nativeSelection.anchorNode.nodeType === Node.TEXT_NODE) { + // See isTabHTMLSpanElement in chromium EditingUtilities.cpp. + var parentNode = nativeSelection.anchorNode.parentNode; + mustPreventNative = parentNode.nodeName === 'SPAN' && parentNode.firstChild.nodeType === Node.TEXT_NODE && parentNode.firstChild.nodeValue.indexOf('\t') !== -1; + } + } + if (!mustPreventNative) { + // Check the old and new "fingerprints" of the current block to determine + // whether this insertion requires any addition or removal of text nodes, + // in which case we would prevent the native character insertion. + var originalFingerprint = BlockTree.getFingerprint(editorState.getBlockTree(anchorKey)); + var newFingerprint = BlockTree.getFingerprint(newEditorState.getBlockTree(anchorKey)); + mustPreventNative = originalFingerprint !== newFingerprint; + } + if (!mustPreventNative) { + mustPreventNative = mustPreventDefaultForCharacter(chars); + } + if (!mustPreventNative) { + mustPreventNative = nullthrows(newEditorState.getDirectionMap()).get(anchorKey) !== nullthrows(editorState.getDirectionMap()).get(anchorKey); + } + + if (mustPreventNative) { + e.preventDefault(); + editor.update(newEditorState); + return; + } + + // We made it all the way! Let the browser do its thing and insert the char. + newEditorState = EditorState.set(newEditorState, { + nativelyRenderedContent: newEditorState.getCurrentContent() + }); + // The native event is allowed to occur. To allow user onChange handlers to + // change the inserted text, we wait until the text is actually inserted + // before we actually update our state. That way when we rerender, the text + // we see in the DOM will already have been inserted properly. + editor._pendingStateFromBeforeInput = newEditorState; + setImmediate(function () { + if (editor._pendingStateFromBeforeInput !== undefined) { + editor.update(editor._pendingStateFromBeforeInput); + editor._pendingStateFromBeforeInput = undefined; + } + }); +} + +module.exports = editOnBeforeInput; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) + +/***/ }), +/* 126 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnBlur + * @format + * + */ + + + +var EditorState = __webpack_require__(3); + +var containsNode = __webpack_require__(39); +var getActiveElement = __webpack_require__(75); + +function editOnBlur(editor, e) { + // In a contentEditable element, when you select a range and then click + // another active element, this does trigger a `blur` event but will not + // remove the DOM selection from the contenteditable. + // This is consistent across all browsers, but we prefer that the editor + // behave like a textarea, where a `blur` event clears the DOM selection. + // We therefore force the issue to be certain, checking whether the active + // element is `body` to force it when blurring occurs within the window (as + // opposed to clicking to another tab or window). + if (getActiveElement() === document.body) { + var _selection = global.getSelection(); + var editorNode = editor.editor; + if (_selection.rangeCount === 1 && containsNode(editorNode, _selection.anchorNode) && containsNode(editorNode, _selection.focusNode)) { + _selection.removeAllRanges(); + } + } + + var editorState = editor._latestEditorState; + var currentSelection = editorState.getSelection(); + if (!currentSelection.getHasFocus()) { + return; + } + + var selection = currentSelection.set('hasFocus', false); + editor.props.onBlur && editor.props.onBlur(e); + editor.update(EditorState.acceptSelection(editorState, selection)); +} + +module.exports = editOnBlur; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) + +/***/ }), +/* 127 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnCompositionStart + * @format + * + */ + + + +var EditorState = __webpack_require__(3); + +/** + * The user has begun using an IME input system. Switching to `composite` mode + * allows handling composition input and disables other edit behavior. + */ +function editOnCompositionStart(editor, e) { + editor.setMode('composite'); + editor.update(EditorState.set(editor._latestEditorState, { inCompositionMode: true })); + // Allow composition handler to interpret the compositionstart event + editor._onCompositionStart(e); +} + +module.exports = editOnCompositionStart; + +/***/ }), +/* 128 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnCopy + * @format + * + */ + + + +var getFragmentFromSelection = __webpack_require__(60); + +/** + * If we have a selection, create a ContentState fragment and store + * it in our internal clipboard. Subsequent paste events will use this + * fragment if no external clipboard data is supplied. + */ +function editOnCopy(editor, e) { + var editorState = editor._latestEditorState; + var selection = editorState.getSelection(); + + // No selection, so there's nothing to copy. + if (selection.isCollapsed()) { + e.preventDefault(); + return; + } + + editor.setClipboard(getFragmentFromSelection(editor._latestEditorState)); +} + +module.exports = editOnCopy; + +/***/ }), +/* 129 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnCut + * @format + * + */ + + + +var DraftModifier = __webpack_require__(6); +var EditorState = __webpack_require__(3); +var Style = __webpack_require__(37); + +var getFragmentFromSelection = __webpack_require__(60); +var getScrollPosition = __webpack_require__(41); + +/** + * On `cut` events, native behavior is allowed to occur so that the system + * clipboard is set properly. This means that we need to take steps to recover + * the editor DOM state after the `cut` has occurred in order to maintain + * control of the component. + * + * In addition, we can keep a copy of the removed fragment, including all + * styles and entities, for use as an internal paste. + */ +function editOnCut(editor, e) { + var editorState = editor._latestEditorState; + var selection = editorState.getSelection(); + var element = e.target; + var scrollPosition = void 0; + + // No selection, so there's nothing to cut. + if (selection.isCollapsed()) { + e.preventDefault(); + return; + } + + // Track the current scroll position so that it can be forced back in place + // after the editor regains control of the DOM. + if (element instanceof Node) { + scrollPosition = getScrollPosition(Style.getScrollParent(element)); + } + + var fragment = getFragmentFromSelection(editorState); + editor.setClipboard(fragment); + + // Set `cut` mode to disable all event handling temporarily. + editor.setMode('cut'); + + // Let native `cut` behavior occur, then recover control. + setTimeout(function () { + editor.restoreEditorDOM(scrollPosition); + editor.exitCurrentMode(); + editor.update(removeFragment(editorState)); + }, 0); +} + +function removeFragment(editorState) { + var newContent = DraftModifier.removeRange(editorState.getCurrentContent(), editorState.getSelection(), 'forward'); + return EditorState.push(editorState, newContent, 'remove-range'); +} + +module.exports = editOnCut; + +/***/ }), +/* 130 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnDragOver + * @format + * + */ + + + +/** + * Drag behavior has begun from outside the editor element. + */ +function editOnDragOver(editor, e) { + editor._internalDrag = false; + editor.setMode('drag'); + e.preventDefault(); +} + +module.exports = editOnDragOver; + +/***/ }), +/* 131 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnDragStart + * @format + * + */ + + + +/** + * A `dragstart` event has begun within the text editor component. + */ +function editOnDragStart(editor) { + editor._internalDrag = true; + editor.setMode('drag'); +} + +module.exports = editOnDragStart; + +/***/ }), +/* 132 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnFocus + * @format + * + */ + + + +var EditorState = __webpack_require__(3); +var UserAgent = __webpack_require__(12); + +function editOnFocus(editor, e) { + var editorState = editor._latestEditorState; + var currentSelection = editorState.getSelection(); + if (currentSelection.getHasFocus()) { + return; + } + + var selection = currentSelection.set('hasFocus', true); + editor.props.onFocus && editor.props.onFocus(e); + + // When the tab containing this text editor is hidden and the user does a + // find-in-page in a _different_ tab, Chrome on Mac likes to forget what the + // selection was right after sending this focus event and (if you let it) + // moves the cursor back to the beginning of the editor, so we force the + // selection here instead of simply accepting it in order to preserve the + // old cursor position. See https://crbug.com/540004. + // But it looks like this is fixed in Chrome 60.0.3081.0. + // Other browsers also don't have this bug, so we prefer to acceptSelection + // when possible, to ensure that unfocusing and refocusing a Draft editor + // doesn't preserve the selection, matching how textareas work. + if (UserAgent.isBrowser('Chrome < 60.0.3081.0')) { + editor.update(EditorState.forceSelection(editorState, selection)); + } else { + editor.update(EditorState.acceptSelection(editorState, selection)); + } +} + +module.exports = editOnFocus; + +/***/ }), +/* 133 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnInput + * @format + * + */ + + + +var DraftFeatureFlags = __webpack_require__(14); +var DraftModifier = __webpack_require__(6); +var DraftOffsetKey = __webpack_require__(26); +var EditorState = __webpack_require__(3); +var UserAgent = __webpack_require__(12); + +var findAncestorOffsetKey = __webpack_require__(32); +var nullthrows = __webpack_require__(10); + +var isGecko = UserAgent.isEngine('Gecko'); + +var DOUBLE_NEWLINE = '\n\n'; + +/** + * This function is intended to handle spellcheck and autocorrect changes, + * which occur in the DOM natively without any opportunity to observe or + * interpret the changes before they occur. + * + * The `input` event fires in contentEditable elements reliably for non-IE + * browsers, immediately after changes occur to the editor DOM. Since our other + * handlers override or otherwise handle cover other varieties of text input, + * the DOM state should match the model in all controlled input cases. Thus, + * when an `input` change leads to a DOM/model mismatch, the change should be + * due to a spellcheck change, and we can incorporate it into our model. + */ +function editOnInput(editor) { + if (editor._pendingStateFromBeforeInput !== undefined) { + editor.update(editor._pendingStateFromBeforeInput); + editor._pendingStateFromBeforeInput = undefined; + } + + var domSelection = global.getSelection(); + + var anchorNode = domSelection.anchorNode, + isCollapsed = domSelection.isCollapsed; + + var isNotTextNode = anchorNode.nodeType !== Node.TEXT_NODE; + var isNotTextOrElementNode = anchorNode.nodeType !== Node.TEXT_NODE && anchorNode.nodeType !== Node.ELEMENT_NODE; + + if (DraftFeatureFlags.draft_killswitch_allow_nontextnodes) { + if (isNotTextNode) { + return; + } + } else { + if (isNotTextOrElementNode) { + // TODO: (t16149272) figure out context for this change + return; + } + } + + if (anchorNode.nodeType === Node.TEXT_NODE && (anchorNode.previousSibling !== null || anchorNode.nextSibling !== null)) { + // When typing at the beginning of a visual line, Chrome splits the text + // nodes into two. Why? No one knows. This commit is suspicious: + // https://chromium.googlesource.com/chromium/src/+/a3b600981286b135632371477f902214c55a1724 + // To work around, we'll merge the sibling text nodes back into this one. + var span = anchorNode.parentNode; + anchorNode.nodeValue = span.textContent; + for (var child = span.firstChild; child !== null; child = child.nextSibling) { + if (child !== anchorNode) { + span.removeChild(child); + } + } + } + + var domText = anchorNode.textContent; + var editorState = editor._latestEditorState; + var offsetKey = nullthrows(findAncestorOffsetKey(anchorNode)); + + var _DraftOffsetKey$decod = DraftOffsetKey.decode(offsetKey), + blockKey = _DraftOffsetKey$decod.blockKey, + decoratorKey = _DraftOffsetKey$decod.decoratorKey, + leafKey = _DraftOffsetKey$decod.leafKey; + + var _editorState$getBlock = editorState.getBlockTree(blockKey).getIn([decoratorKey, 'leaves', leafKey]), + start = _editorState$getBlock.start, + end = _editorState$getBlock.end; + + var content = editorState.getCurrentContent(); + var block = content.getBlockForKey(blockKey); + var modelText = block.getText().slice(start, end); + + // Special-case soft newlines here. If the DOM text ends in a soft newline, + // we will have manually inserted an extra soft newline in DraftEditorLeaf. + // We want to remove this extra newline for the purpose of our comparison + // of DOM and model text. + if (domText.endsWith(DOUBLE_NEWLINE)) { + domText = domText.slice(0, -1); + } + + // No change -- the DOM is up to date. Nothing to do here. + if (domText === modelText) { + // This can be buggy for some Android keyboards because they don't fire + // standard onkeydown/pressed events and only fired editOnInput + // so domText is already changed by the browser and ends up being equal + // to modelText unexpectedly + return; + } + + var selection = editorState.getSelection(); + + // We'll replace the entire leaf with the text content of the target. + var targetRange = selection.merge({ + anchorOffset: start, + focusOffset: end, + isBackward: false + }); + + var entityKey = block.getEntityAt(start); + var entity = entityKey && content.getEntity(entityKey); + var entityType = entity && entity.getMutability(); + var preserveEntity = entityType === 'MUTABLE'; + + // Immutable or segmented entities cannot properly be handled by the + // default browser undo, so we have to use a different change type to + // force using our internal undo method instead of falling through to the + // native browser undo. + var changeType = preserveEntity ? 'spellcheck-change' : 'apply-entity'; + + var newContent = DraftModifier.replaceText(content, targetRange, domText, block.getInlineStyleAt(start), preserveEntity ? block.getEntityAt(start) : null); + + var anchorOffset, focusOffset, startOffset, endOffset; + + if (isGecko) { + // Firefox selection does not change while the context menu is open, so + // we preserve the anchor and focus values of the DOM selection. + anchorOffset = domSelection.anchorOffset; + focusOffset = domSelection.focusOffset; + startOffset = start + Math.min(anchorOffset, focusOffset); + endOffset = startOffset + Math.abs(anchorOffset - focusOffset); + anchorOffset = startOffset; + focusOffset = endOffset; + } else { + // Browsers other than Firefox may adjust DOM selection while the context + // menu is open, and Safari autocorrect is prone to providing an inaccurate + // DOM selection. Don't trust it. Instead, use our existing SelectionState + // and adjust it based on the number of characters changed during the + // mutation. + var charDelta = domText.length - modelText.length; + startOffset = selection.getStartOffset(); + endOffset = selection.getEndOffset(); + + anchorOffset = isCollapsed ? endOffset + charDelta : startOffset; + focusOffset = endOffset + charDelta; + } + + // Segmented entities are completely or partially removed when their + // text content changes. For this case we do not want any text to be selected + // after the change, so we are not merging the selection. + var contentWithAdjustedDOMSelection = newContent.merge({ + selectionBefore: content.getSelectionAfter(), + selectionAfter: selection.merge({ anchorOffset: anchorOffset, focusOffset: focusOffset }) + }); + + editor.update(EditorState.push(editorState, contentWithAdjustedDOMSelection, changeType)); +} + +module.exports = editOnInput; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) + +/***/ }), +/* 134 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnKeyDown + * @format + * + */ + + + +var DraftModifier = __webpack_require__(6); +var EditorState = __webpack_require__(3); +var KeyBindingUtil = __webpack_require__(31); +var Keys = __webpack_require__(36); +var SecondaryClipboard = __webpack_require__(116); +var UserAgent = __webpack_require__(12); + +var isEventHandled = __webpack_require__(22); +var keyCommandBackspaceToStartOfLine = __webpack_require__(147); +var keyCommandBackspaceWord = __webpack_require__(148); +var keyCommandDeleteWord = __webpack_require__(149); +var keyCommandInsertNewline = __webpack_require__(150); +var keyCommandMoveSelectionToEndOfBlock = __webpack_require__(151); +var keyCommandMoveSelectionToStartOfBlock = __webpack_require__(152); +var keyCommandPlainBackspace = __webpack_require__(153); +var keyCommandPlainDelete = __webpack_require__(154); +var keyCommandTransposeCharacters = __webpack_require__(155); +var keyCommandUndo = __webpack_require__(156); + +var isOptionKeyCommand = KeyBindingUtil.isOptionKeyCommand; + +var isChrome = UserAgent.isBrowser('Chrome'); + +/** + * Map a `DraftEditorCommand` command value to a corresponding function. + */ +function onKeyCommand(command, editorState) { + switch (command) { + case 'redo': + return EditorState.redo(editorState); + case 'delete': + return keyCommandPlainDelete(editorState); + case 'delete-word': + return keyCommandDeleteWord(editorState); + case 'backspace': + return keyCommandPlainBackspace(editorState); + case 'backspace-word': + return keyCommandBackspaceWord(editorState); + case 'backspace-to-start-of-line': + return keyCommandBackspaceToStartOfLine(editorState); + case 'split-block': + return keyCommandInsertNewline(editorState); + case 'transpose-characters': + return keyCommandTransposeCharacters(editorState); + case 'move-selection-to-start-of-block': + return keyCommandMoveSelectionToStartOfBlock(editorState); + case 'move-selection-to-end-of-block': + return keyCommandMoveSelectionToEndOfBlock(editorState); + case 'secondary-cut': + return SecondaryClipboard.cut(editorState); + case 'secondary-paste': + return SecondaryClipboard.paste(editorState); + default: + return editorState; + } +} + +/** + * Intercept keydown behavior to handle keys and commands manually, if desired. + * + * Keydown combinations may be mapped to `DraftCommand` values, which may + * correspond to command functions that modify the editor or its contents. + * + * See `getDefaultKeyBinding` for defaults. Alternatively, the top-level + * component may provide a custom mapping via the `keyBindingFn` prop. + */ +function editOnKeyDown(editor, e) { + var keyCode = e.which; + var editorState = editor._latestEditorState; + + switch (keyCode) { + case Keys.RETURN: + e.preventDefault(); + // The top-level component may manually handle newline insertion. If + // no special handling is performed, fall through to command handling. + if (editor.props.handleReturn && isEventHandled(editor.props.handleReturn(e, editorState))) { + return; + } + break; + case Keys.ESC: + e.preventDefault(); + editor.props.onEscape && editor.props.onEscape(e); + return; + case Keys.TAB: + editor.props.onTab && editor.props.onTab(e); + return; + case Keys.UP: + editor.props.onUpArrow && editor.props.onUpArrow(e); + return; + case Keys.RIGHT: + editor.props.onRightArrow && editor.props.onRightArrow(e); + return; + case Keys.DOWN: + editor.props.onDownArrow && editor.props.onDownArrow(e); + return; + case Keys.LEFT: + editor.props.onLeftArrow && editor.props.onLeftArrow(e); + return; + case Keys.SPACE: + // Handling for OSX where option + space scrolls. + if (isChrome && isOptionKeyCommand(e)) { + e.preventDefault(); + // Insert a nbsp into the editor. + var contentState = DraftModifier.replaceText(editorState.getCurrentContent(), editorState.getSelection(), '\xA0'); + editor.update(EditorState.push(editorState, contentState, 'insert-characters')); + return; + } + } + + var command = editor.props.keyBindingFn(e); + + // If no command is specified, allow keydown event to continue. + if (!command) { + return; + } + + if (command === 'undo') { + // Since undo requires some special updating behavior to keep the editor + // in sync, handle it separately. + keyCommandUndo(e, editorState, editor.update); + return; + } + + // At this point, we know that we're handling a command of some kind, so + // we don't want to insert a character following the keydown. + e.preventDefault(); + + // Allow components higher up the tree to handle the command first. + if (editor.props.handleKeyCommand && isEventHandled(editor.props.handleKeyCommand(command, editorState))) { + return; + } + + var newState = onKeyCommand(command, editorState); + if (newState !== editorState) { + editor.update(newState); + } +} + +module.exports = editOnKeyDown; + +/***/ }), +/* 135 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnPaste + * @format + * + */ + + + +var BlockMapBuilder = __webpack_require__(20); +var CharacterMetadata = __webpack_require__(7); +var DataTransfer = __webpack_require__(72); +var DraftModifier = __webpack_require__(6); +var DraftPasteProcessor = __webpack_require__(113); +var EditorState = __webpack_require__(3); +var RichTextEditorUtil = __webpack_require__(56); + +var getEntityKeyForSelection = __webpack_require__(33); +var getTextContentFromFiles = __webpack_require__(65); +var isEventHandled = __webpack_require__(22); +var splitTextIntoTextBlocks = __webpack_require__(162); + +/** + * Paste content. + */ +function editOnPaste(editor, e) { + e.preventDefault(); + var data = new DataTransfer(e.clipboardData); + + // Get files, unless this is likely to be a string the user wants inline. + if (!data.isRichText()) { + var files = data.getFiles(); + var defaultFileText = data.getText(); + if (files.length > 0) { + // Allow customized paste handling for images, etc. Otherwise, fall + // through to insert text contents into the editor. + if (editor.props.handlePastedFiles && isEventHandled(editor.props.handlePastedFiles(files))) { + return; + } + + getTextContentFromFiles(files, function ( /*string*/fileText) { + fileText = fileText || defaultFileText; + if (!fileText) { + return; + } + + var editorState = editor._latestEditorState; + var blocks = splitTextIntoTextBlocks(fileText); + var character = CharacterMetadata.create({ + style: editorState.getCurrentInlineStyle(), + entity: getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection()) + }); + var currentBlockType = RichTextEditorUtil.getCurrentBlockType(editorState); + + var text = DraftPasteProcessor.processText(blocks, character, currentBlockType); + var fragment = BlockMapBuilder.createFromArray(text); + + var withInsertedText = DraftModifier.replaceWithFragment(editorState.getCurrentContent(), editorState.getSelection(), fragment); + + editor.update(EditorState.push(editorState, withInsertedText, 'insert-fragment')); + }); + + return; + } + } + + var textBlocks = []; + var text = data.getText(); + var html = data.getHTML(); + var editorState = editor._latestEditorState; + + if (editor.props.handlePastedText && isEventHandled(editor.props.handlePastedText(text, html, editorState))) { + return; + } + + if (text) { + textBlocks = splitTextIntoTextBlocks(text); + } + + if (!editor.props.stripPastedStyles) { + // If the text from the paste event is rich content that matches what we + // already have on the internal clipboard, assume that we should just use + // the clipboard fragment for the paste. This will allow us to preserve + // styling and entities, if any are present. Note that newlines are + // stripped during comparison -- this is because copy/paste within the + // editor in Firefox and IE will not include empty lines. The resulting + // paste will preserve the newlines correctly. + var internalClipboard = editor.getClipboard(); + if (data.isRichText() && internalClipboard) { + if ( + // If the editorKey is present in the pasted HTML, it should be safe to + // assume this is an internal paste. + html.indexOf(editor.getEditorKey()) !== -1 || + // The copy may have been made within a single block, in which case the + // editor key won't be part of the paste. In this case, just check + // whether the pasted text matches the internal clipboard. + textBlocks.length === 1 && internalClipboard.size === 1 && internalClipboard.first().getText() === text) { + editor.update(insertFragment(editor._latestEditorState, internalClipboard)); + return; + } + } else if (internalClipboard && data.types.includes('com.apple.webarchive') && !data.types.includes('text/html') && areTextBlocksAndClipboardEqual(textBlocks, internalClipboard)) { + // Safari does not properly store text/html in some cases. + // Use the internalClipboard if present and equal to what is on + // the clipboard. See https://bugs.webkit.org/show_bug.cgi?id=19893. + editor.update(insertFragment(editor._latestEditorState, internalClipboard)); + return; + } + + // If there is html paste data, try to parse that. + if (html) { + var htmlFragment = DraftPasteProcessor.processHTML(html, editor.props.blockRenderMap); + if (htmlFragment) { + var contentBlocks = htmlFragment.contentBlocks, + entityMap = htmlFragment.entityMap; + + if (contentBlocks) { + var htmlMap = BlockMapBuilder.createFromArray(contentBlocks); + editor.update(insertFragment(editor._latestEditorState, htmlMap, entityMap)); + return; + } + } + } + + // Otherwise, create a new fragment from our pasted text. Also + // empty the internal clipboard, since it's no longer valid. + editor.setClipboard(null); + } + + if (textBlocks.length) { + var character = CharacterMetadata.create({ + style: editorState.getCurrentInlineStyle(), + entity: getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection()) + }); + + var currentBlockType = RichTextEditorUtil.getCurrentBlockType(editorState); + + var textFragment = DraftPasteProcessor.processText(textBlocks, character, currentBlockType); + + var textMap = BlockMapBuilder.createFromArray(textFragment); + editor.update(insertFragment(editor._latestEditorState, textMap)); + } +} + +function insertFragment(editorState, fragment, entityMap) { + var newContent = DraftModifier.replaceWithFragment(editorState.getCurrentContent(), editorState.getSelection(), fragment); + // TODO: merge the entity map once we stop using DraftEntity + // like this: + // const mergedEntityMap = newContent.getEntityMap().merge(entityMap); + + return EditorState.push(editorState, newContent.set('entityMap', entityMap), 'insert-fragment'); +} + +function areTextBlocksAndClipboardEqual(textBlocks, blockMap) { + return textBlocks.length === blockMap.size && blockMap.valueSeq().every(function (block, ii) { + return block.getText() === textBlocks[ii]; + }); +} + +module.exports = editOnPaste; + +/***/ }), +/* 136 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule editOnSelect + * @format + * + */ + + + +var EditorState = __webpack_require__(3); +var ReactDOM = __webpack_require__(17); + +var getDraftEditorSelection = __webpack_require__(141); +var invariant = __webpack_require__(2); + +function editOnSelect(editor) { + if (editor._blockSelectEvents || editor._latestEditorState !== editor.props.editorState) { + return; + } + + var editorState = editor.props.editorState; + var editorNode = ReactDOM.findDOMNode(editor.editorContainer); + !editorNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing editorNode') : invariant(false) : void 0; + !(editorNode.firstChild instanceof HTMLElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'editorNode.firstChild is not an HTMLElement') : invariant(false) : void 0; + var documentSelection = getDraftEditorSelection(editorState, editorNode.firstChild); + var updatedSelectionState = documentSelection.selectionState; + + if (updatedSelectionState !== editorState.getSelection()) { + if (documentSelection.needsRecovery) { + editorState = EditorState.forceSelection(editorState, updatedSelectionState); + } else { + editorState = EditorState.acceptSelection(editorState, updatedSelectionState); + } + editor.update(editorState); + } +} + +module.exports = editOnSelect; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 137 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule encodeEntityRanges + * @format + * + */ + + + +var DraftStringKey = __webpack_require__(55); +var UnicodeUtils = __webpack_require__(16); + +var strlen = UnicodeUtils.strlen; + +/** + * Convert to UTF-8 character counts for storage. + */ + +function encodeEntityRanges(block, storageMap) { + var encoded = []; + block.findEntityRanges(function (character) { + return !!character.getEntity(); + }, function ( /*number*/start, /*number*/end) { + var text = block.getText(); + var key = block.getEntityAt(start); + encoded.push({ + offset: strlen(text.slice(0, start)), + length: strlen(text.slice(start, end)), + // Encode the key as a number for range storage. + key: Number(storageMap[DraftStringKey.stringify(key)]) + }); + }); + return encoded; +} + +module.exports = encodeEntityRanges; + +/***/ }), +/* 138 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule encodeInlineStyleRanges + * @format + * + */ + + + +var UnicodeUtils = __webpack_require__(16); + +var findRangesImmutable = __webpack_require__(21); + +var areEqual = function areEqual(a, b) { + return a === b; +}; +var isTruthy = function isTruthy(a) { + return !!a; +}; +var EMPTY_ARRAY = []; + +/** + * Helper function for getting encoded styles for each inline style. Convert + * to UTF-8 character counts for storage. + */ +function getEncodedInlinesForType(block, styleList, styleToEncode) { + var ranges = []; + + // Obtain an array with ranges for only the specified style. + var filteredInlines = styleList.map(function (style) { + return style.has(styleToEncode); + }).toList(); + + findRangesImmutable(filteredInlines, areEqual, + // We only want to keep ranges with nonzero style values. + isTruthy, function (start, end) { + var text = block.getText(); + ranges.push({ + offset: UnicodeUtils.strlen(text.slice(0, start)), + length: UnicodeUtils.strlen(text.slice(start, end)), + style: styleToEncode + }); + }); + + return ranges; +} + +/* + * Retrieve the encoded arrays of inline styles, with each individual style + * treated separately. + */ +function encodeInlineStyleRanges(block) { + var styleList = block.getCharacterList().map(function (c) { + return c.getStyle(); + }).toList(); + var ranges = styleList.flatten().toSet().map(function (style) { + return getEncodedInlinesForType(block, styleList, style); + }); + + return Array.prototype.concat.apply(EMPTY_ARRAY, ranges.toJS()); +} + +module.exports = encodeInlineStyleRanges; + +/***/ }), +/* 139 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) { + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule expandRangeToStartOfLine + * @format + * + */ + +var UnicodeUtils = __webpack_require__(16); + +var getRangeClientRects = __webpack_require__(62); +var invariant = __webpack_require__(2); + +/** + * Return the computed line height, in pixels, for the provided element. + */ +function getLineHeightPx(element) { + var computed = getComputedStyle(element); + var div = document.createElement('div'); + div.style.fontFamily = computed.fontFamily; + div.style.fontSize = computed.fontSize; + div.style.fontStyle = computed.fontStyle; + div.style.fontWeight = computed.fontWeight; + div.style.lineHeight = computed.lineHeight; + div.style.position = 'absolute'; + div.textContent = 'M'; + + var documentBody = document.body; + !documentBody ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing document.body') : invariant(false) : void 0; + + // forced layout here + documentBody.appendChild(div); + var rect = div.getBoundingClientRect(); + documentBody.removeChild(div); + + return rect.height; +} + +/** + * Return whether every ClientRect in the provided list lies on the same line. + * + * We assume that the rects on the same line all contain the baseline, so the + * lowest top line needs to be above the highest bottom line (i.e., if you were + * to project the rects onto the y-axis, their intersection would be nonempty). + * + * In addition, we require that no two boxes are lineHeight (or more) apart at + * either top or bottom, which helps protect against false positives for fonts + * with extremely large glyph heights (e.g., with a font size of 17px, Zapfino + * produces rects of height 58px!). + */ +function areRectsOnOneLine(rects, lineHeight) { + var minTop = Infinity; + var minBottom = Infinity; + var maxTop = -Infinity; + var maxBottom = -Infinity; + + for (var ii = 0; ii < rects.length; ii++) { + var rect = rects[ii]; + if (rect.width === 0 || rect.width === 1) { + // When a range starts or ends a soft wrap, many browsers (Chrome, IE, + // Safari) include an empty rect on the previous or next line. When the + // text lies in a container whose position is not integral (e.g., from + // margin: auto), Safari makes these empty rects have width 1 (instead of + // 0). Having one-pixel-wide characters seems unlikely (and most browsers + // report widths in subpixel precision anyway) so it's relatively safe to + // skip over them. + continue; + } + minTop = Math.min(minTop, rect.top); + minBottom = Math.min(minBottom, rect.bottom); + maxTop = Math.max(maxTop, rect.top); + maxBottom = Math.max(maxBottom, rect.bottom); + } + + return maxTop <= minBottom && maxTop - minTop < lineHeight && maxBottom - minBottom < lineHeight; +} + +/** + * Return the length of a node, as used by Range offsets. + */ +function getNodeLength(node) { + // http://www.w3.org/TR/dom/#concept-node-length + switch (node.nodeType) { + case Node.DOCUMENT_TYPE_NODE: + return 0; + case Node.TEXT_NODE: + case Node.PROCESSING_INSTRUCTION_NODE: + case Node.COMMENT_NODE: + return node.length; + default: + return node.childNodes.length; + } +} + +/** + * Given a collapsed range, move the start position backwards as far as + * possible while the range still spans only a single line. + */ +function expandRangeToStartOfLine(range) { + !range.collapsed ? process.env.NODE_ENV !== 'production' ? invariant(false, 'expandRangeToStartOfLine: Provided range is not collapsed.') : invariant(false) : void 0; + range = range.cloneRange(); + + var containingElement = range.startContainer; + if (containingElement.nodeType !== 1) { + containingElement = containingElement.parentNode; + } + var lineHeight = getLineHeightPx(containingElement); + + // Imagine our text looks like: + //
once upon a time, there was a boy + // who lived under^ the + // stairs in a small closet.
+ // where the caret represents the cursor. First, we crawl up the tree until + // the range spans multiple lines (setting the start point to before + // "", then before "
"), then at each level we do a search to + // find the latest point which is still on a previous line. We'll find that + // the break point is inside the span, then inside the , then in its text + // node child, the actual break point before "who". + + var bestContainer = range.endContainer; + var bestOffset = range.endOffset; + range.setStart(range.startContainer, 0); + + while (areRectsOnOneLine(getRangeClientRects(range), lineHeight)) { + bestContainer = range.startContainer; + bestOffset = range.startOffset; + !bestContainer.parentNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Found unexpected detached subtree when traversing.') : invariant(false) : void 0; + range.setStartBefore(bestContainer); + if (bestContainer.nodeType === 1 && getComputedStyle(bestContainer).display !== 'inline') { + // The start of the line is never in a different block-level container. + break; + } + } + + // In the above example, range now spans from "
" to "under", + // bestContainer is
, and bestOffset is 1 (index of inside
)]. + // Picking out which child to recurse into here is a special case since we + // don't want to check past -- once we find that the final range starts + // in , we can look at all of its children (and all of their children) + // to find the break point. + + // At all times, (bestContainer, bestOffset) is the latest single-line start + // point that we know of. + var currentContainer = bestContainer; + var maxIndexToConsider = bestOffset - 1; + + do { + var nodeValue = currentContainer.nodeValue; + + for (var ii = maxIndexToConsider; ii >= 0; ii--) { + if (nodeValue != null && ii > 0 && UnicodeUtils.isSurrogatePair(nodeValue, ii - 1)) { + // We're in the middle of a surrogate pair -- skip over so we never + // return a range with an endpoint in the middle of a code point. + continue; + } + + range.setStart(currentContainer, ii); + if (areRectsOnOneLine(getRangeClientRects(range), lineHeight)) { + bestContainer = currentContainer; + bestOffset = ii; + } else { + break; + } + } + + if (ii === -1 || currentContainer.childNodes.length === 0) { + // If ii === -1, then (bestContainer, bestOffset), which is equal to + // (currentContainer, 0), was a single-line start point but a start + // point before currentContainer wasn't, so the line break seems to + // have occurred immediately after currentContainer's start tag + // + // If currentContainer.childNodes.length === 0, we're already at a + // terminal node (e.g., text node) and should return our current best. + break; + } + + currentContainer = currentContainer.childNodes[ii]; + maxIndexToConsider = getNodeLength(currentContainer); + } while (true); + + range.setStart(bestContainer, bestOffset); + return range; +} + +module.exports = expandRangeToStartOfLine; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 140 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getCharacterRemovalRange + * @format + * + */ + + + +var DraftEntitySegments = __webpack_require__(110); + +var getRangesForDraftEntity = __webpack_require__(143); +var invariant = __webpack_require__(2); + +/** + * Given a SelectionState and a removal direction, determine the entire range + * that should be removed from a ContentState. This is based on any entities + * within the target, with their `mutability` values taken into account. + * + * For instance, if we are attempting to remove part of an "immutable" entity + * range, the entire entity must be removed. The returned `SelectionState` + * will be adjusted accordingly. + */ +function getCharacterRemovalRange(entityMap, startBlock, endBlock, selectionState, direction) { + var start = selectionState.getStartOffset(); + var end = selectionState.getEndOffset(); + var startEntityKey = startBlock.getEntityAt(start); + var endEntityKey = endBlock.getEntityAt(end - 1); + if (!startEntityKey && !endEntityKey) { + return selectionState; + } + var newSelectionState = selectionState; + if (startEntityKey && startEntityKey === endEntityKey) { + newSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, true, true); + } else if (startEntityKey && endEntityKey) { + var startSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, false, true); + var endSelectionState = getEntityRemovalRange(entityMap, endBlock, newSelectionState, direction, endEntityKey, false, false); + newSelectionState = newSelectionState.merge({ + anchorOffset: startSelectionState.getAnchorOffset(), + focusOffset: endSelectionState.getFocusOffset(), + isBackward: false + }); + } else if (startEntityKey) { + var _startSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, false, true); + newSelectionState = newSelectionState.merge({ + anchorOffset: _startSelectionState.getStartOffset(), + isBackward: false + }); + } else if (endEntityKey) { + var _endSelectionState = getEntityRemovalRange(entityMap, endBlock, newSelectionState, direction, endEntityKey, false, false); + newSelectionState = newSelectionState.merge({ + focusOffset: _endSelectionState.getEndOffset(), + isBackward: false + }); + } + return newSelectionState; +} + +function getEntityRemovalRange(entityMap, block, selectionState, direction, entityKey, isEntireSelectionWithinEntity, isEntityAtStart) { + var start = selectionState.getStartOffset(); + var end = selectionState.getEndOffset(); + var entity = entityMap.__get(entityKey); + var mutability = entity.getMutability(); + var sideToConsider = isEntityAtStart ? start : end; + + // `MUTABLE` entities can just have the specified range of text removed + // directly. No adjustments are needed. + if (mutability === 'MUTABLE') { + return selectionState; + } + + // Find the entity range that overlaps with our removal range. + var entityRanges = getRangesForDraftEntity(block, entityKey).filter(function (range) { + return sideToConsider <= range.end && sideToConsider >= range.start; + }); + + !(entityRanges.length == 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There should only be one entity range within this removal range.') : invariant(false) : void 0; + + var entityRange = entityRanges[0]; + + // For `IMMUTABLE` entity types, we will remove the entire entity range. + if (mutability === 'IMMUTABLE') { + return selectionState.merge({ + anchorOffset: entityRange.start, + focusOffset: entityRange.end, + isBackward: false + }); + } + + // For `SEGMENTED` entity types, determine the appropriate segment to + // remove. + if (!isEntireSelectionWithinEntity) { + if (isEntityAtStart) { + end = entityRange.end; + } else { + start = entityRange.start; + } + } + + var removalRange = DraftEntitySegments.getRemovalRange(start, end, block.getText().slice(entityRange.start, entityRange.end), entityRange.start, direction); + + return selectionState.merge({ + anchorOffset: removalRange.start, + focusOffset: removalRange.end, + isBackward: false + }); +} + +module.exports = getCharacterRemovalRange; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 141 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getDraftEditorSelection + * @format + * + */ + + + +var getDraftEditorSelectionWithNodes = __webpack_require__(59); + +/** + * Convert the current selection range to an anchor/focus pair of offset keys + * and values that can be interpreted by components. + */ +function getDraftEditorSelection(editorState, root) { + var selection = global.getSelection(); + + // No active selection. + if (selection.rangeCount === 0) { + return { + selectionState: editorState.getSelection().set('hasFocus', false), + needsRecovery: false + }; + } + + return getDraftEditorSelectionWithNodes(editorState, root, selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); +} + +module.exports = getDraftEditorSelection; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) + +/***/ }), +/* 142 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getRangeBoundingClientRect + * @format + * + */ + + + +var getRangeClientRects = __webpack_require__(62); + +/** + * Like range.getBoundingClientRect() but normalizes for browser bugs. + */ +function getRangeBoundingClientRect(range) { + // "Return a DOMRect object describing the smallest rectangle that includes + // the first rectangle in list and all of the remaining rectangles of which + // the height or width is not zero." + // http://www.w3.org/TR/cssom-view/#dom-range-getboundingclientrect + var rects = getRangeClientRects(range); + var top = 0; + var right = 0; + var bottom = 0; + var left = 0; + + if (rects.length) { + // If the first rectangle has 0 width, we use the second, this is needed + // because Chrome renders a 0 width rectangle when the selection contains + // a line break. + if (rects.length > 1 && rects[0].width === 0) { + var _rects$ = rects[1]; + top = _rects$.top; + right = _rects$.right; + bottom = _rects$.bottom; + left = _rects$.left; + } else { + var _rects$2 = rects[0]; + top = _rects$2.top; + right = _rects$2.right; + bottom = _rects$2.bottom; + left = _rects$2.left; + } + + for (var ii = 1; ii < rects.length; ii++) { + var rect = rects[ii]; + if (rect.height !== 0 && rect.width !== 0) { + top = Math.min(top, rect.top); + right = Math.max(right, rect.right); + bottom = Math.max(bottom, rect.bottom); + left = Math.min(left, rect.left); + } + } + } + + return { + top: top, + right: right, + bottom: bottom, + left: left, + width: right - left, + height: bottom - top + }; +} + +module.exports = getRangeBoundingClientRect; + +/***/ }), +/* 143 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getRangesForDraftEntity + * @format + * + */ + + + +var invariant = __webpack_require__(2); + +/** + * Obtain the start and end positions of the range that has the + * specified entity applied to it. + * + * Entity keys are applied only to contiguous stretches of text, so this + * method searches for the first instance of the entity key and returns + * the subsequent range. + */ +function getRangesForDraftEntity(block, key) { + var ranges = []; + block.findEntityRanges(function (c) { + return c.getEntity() === key; + }, function (start, end) { + ranges.push({ start: start, end: end }); + }); + + !!!ranges.length ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Entity key not found in this range.') : invariant(false) : void 0; + + return ranges; +} + +module.exports = getRangesForDraftEntity; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 144 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule getVisibleSelectionRect + * @format + * + */ + + + +var getRangeBoundingClientRect = __webpack_require__(142); + +/** + * Return the bounding ClientRect for the visible DOM selection, if any. + * In cases where there are no selected ranges or the bounding rect is + * temporarily invalid, return null. + */ +function getVisibleSelectionRect(global) { + var selection = global.getSelection(); + if (!selection.rangeCount) { + return null; + } + + var range = selection.getRangeAt(0); + var boundingRect = getRangeBoundingClientRect(range); + var top = boundingRect.top, + right = boundingRect.right, + bottom = boundingRect.bottom, + left = boundingRect.left; + + // When a re-render leads to a node being removed, the DOM selection will + // temporarily be placed on an ancestor node, which leads to an invalid + // bounding rect. Discard this state. + + if (top === 0 && right === 0 && bottom === 0 && left === 0) { + return null; + } + + return boundingRect; +} + +module.exports = getVisibleSelectionRect; + +/***/ }), +/* 145 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule insertFragmentIntoContentState + * @format + * + */ + + + +var BlockMapBuilder = __webpack_require__(20); +var ContentBlockNode = __webpack_require__(9); +var Immutable = __webpack_require__(1); + +var insertIntoList = __webpack_require__(67); +var invariant = __webpack_require__(2); +var randomizeBlockMapKeys = __webpack_require__(70); + +var List = Immutable.List; + + +var updateExistingBlock = function updateExistingBlock(contentState, selectionState, blockMap, fragmentBlock, targetKey, targetOffset) { + var targetBlock = blockMap.get(targetKey); + var text = targetBlock.getText(); + var chars = targetBlock.getCharacterList(); + var finalKey = targetKey; + var finalOffset = targetOffset + fragmentBlock.getText().length; + + var newBlock = targetBlock.merge({ + text: text.slice(0, targetOffset) + fragmentBlock.getText() + text.slice(targetOffset), + characterList: insertIntoList(chars, fragmentBlock.getCharacterList(), targetOffset), + data: fragmentBlock.getData() + }); + + return contentState.merge({ + blockMap: blockMap.set(targetKey, newBlock), + selectionBefore: selectionState, + selectionAfter: selectionState.merge({ + anchorKey: finalKey, + anchorOffset: finalOffset, + focusKey: finalKey, + focusOffset: finalOffset, + isBackward: false + }) + }); +}; + +/** + * Appends text/characterList from the fragment first block to + * target block. + */ +var updateHead = function updateHead(block, targetOffset, fragment) { + var text = block.getText(); + var chars = block.getCharacterList(); + + // Modify head portion of block. + var headText = text.slice(0, targetOffset); + var headCharacters = chars.slice(0, targetOffset); + var appendToHead = fragment.first(); + + return block.merge({ + text: headText + appendToHead.getText(), + characterList: headCharacters.concat(appendToHead.getCharacterList()), + type: headText ? block.getType() : appendToHead.getType(), + data: appendToHead.getData() + }); +}; + +/** + * Appends offset text/characterList from the target block to the last + * fragment block. + */ +var updateTail = function updateTail(block, targetOffset, fragment) { + // Modify tail portion of block. + var text = block.getText(); + var chars = block.getCharacterList(); + + // Modify head portion of block. + var blockSize = text.length; + var tailText = text.slice(targetOffset, blockSize); + var tailCharacters = chars.slice(targetOffset, blockSize); + var prependToTail = fragment.last(); + + return prependToTail.merge({ + text: prependToTail.getText() + tailText, + characterList: prependToTail.getCharacterList().concat(tailCharacters), + data: prependToTail.getData() + }); +}; + +var getRootBlocks = function getRootBlocks(block, blockMap) { + var headKey = block.getKey(); + var rootBlock = block; + var rootBlocks = []; + + // sometimes the fragment head block will not be part of the blockMap itself this can happen when + // the fragment head is used to update the target block, however when this does not happen we need + // to make sure that we include it on the rootBlocks since the first block of a fragment is always a + // fragment root block + if (blockMap.get(headKey)) { + rootBlocks.push(headKey); + } + + while (rootBlock && rootBlock.getNextSiblingKey()) { + var lastSiblingKey = rootBlock.getNextSiblingKey(); + + if (!lastSiblingKey) { + break; + } + + rootBlocks.push(lastSiblingKey); + rootBlock = blockMap.get(lastSiblingKey); + } + + return rootBlocks; +}; + +var updateBlockMapLinks = function updateBlockMapLinks(blockMap, originalBlockMap, targetBlock, fragmentHeadBlock) { + return blockMap.withMutations(function (blockMapState) { + var targetKey = targetBlock.getKey(); + var headKey = fragmentHeadBlock.getKey(); + var targetNextKey = targetBlock.getNextSiblingKey(); + var targetParentKey = targetBlock.getParentKey(); + var fragmentRootBlocks = getRootBlocks(fragmentHeadBlock, blockMap); + var lastRootFragmentBlockKey = fragmentRootBlocks[fragmentRootBlocks.length - 1]; + + if (blockMapState.get(headKey)) { + // update the fragment head when it is part of the blockMap otherwise + blockMapState.setIn([targetKey, 'nextSibling'], headKey); + blockMapState.setIn([headKey, 'prevSibling'], targetKey); + } else { + // update the target block that had the fragment head contents merged into it + blockMapState.setIn([targetKey, 'nextSibling'], fragmentHeadBlock.getNextSiblingKey()); + blockMapState.setIn([fragmentHeadBlock.getNextSiblingKey(), 'prevSibling'], targetKey); + } + + // update the last root block fragment + blockMapState.setIn([lastRootFragmentBlockKey, 'nextSibling'], targetNextKey); + + // update the original target next block + if (targetNextKey) { + blockMapState.setIn([targetNextKey, 'prevSibling'], lastRootFragmentBlockKey); + } + + // update fragment parent links + fragmentRootBlocks.forEach(function (blockKey) { + return blockMapState.setIn([blockKey, 'parent'], targetParentKey); + }); + + // update targetBlock parent child links + if (targetParentKey) { + var targetParent = blockMap.get(targetParentKey); + var originalTargetParentChildKeys = targetParent.getChildKeys(); + + var targetBlockIndex = originalTargetParentChildKeys.indexOf(targetKey); + var insertionIndex = targetBlockIndex + 1; + + var newChildrenKeysArray = originalTargetParentChildKeys.toArray(); + + // insert fragment children + newChildrenKeysArray.splice.apply(newChildrenKeysArray, [insertionIndex, 0].concat(fragmentRootBlocks)); + + blockMapState.setIn([targetParentKey, 'children'], List(newChildrenKeysArray)); + } + }); +}; + +var insertFragment = function insertFragment(contentState, selectionState, blockMap, fragment, targetKey, targetOffset) { + var isTreeBasedBlockMap = blockMap.first() instanceof ContentBlockNode; + var newBlockArr = []; + var fragmentSize = fragment.size; + var target = blockMap.get(targetKey); + var head = fragment.first(); + var tail = fragment.last(); + var finalOffset = tail.getLength(); + var finalKey = tail.getKey(); + var shouldNotUpdateFromFragmentBlock = isTreeBasedBlockMap && (!target.getChildKeys().isEmpty() || !head.getChildKeys().isEmpty()); + + blockMap.forEach(function (block, blockKey) { + if (blockKey !== targetKey) { + newBlockArr.push(block); + return; + } + + if (shouldNotUpdateFromFragmentBlock) { + newBlockArr.push(block); + } else { + newBlockArr.push(updateHead(block, targetOffset, fragment)); + } + + // Insert fragment blocks after the head and before the tail. + fragment + // when we are updating the target block with the head fragment block we skip the first fragment + // head since its contents have already been merged with the target block otherwise we include + // the whole fragment + .slice(shouldNotUpdateFromFragmentBlock ? 0 : 1, fragmentSize - 1).forEach(function (fragmentBlock) { + return newBlockArr.push(fragmentBlock); + }); + + // update tail + newBlockArr.push(updateTail(block, targetOffset, fragment)); + }); + + var updatedBlockMap = BlockMapBuilder.createFromArray(newBlockArr); + + if (isTreeBasedBlockMap) { + updatedBlockMap = updateBlockMapLinks(updatedBlockMap, blockMap, target, head); + } + + return contentState.merge({ + blockMap: updatedBlockMap, + selectionBefore: selectionState, + selectionAfter: selectionState.merge({ + anchorKey: finalKey, + anchorOffset: finalOffset, + focusKey: finalKey, + focusOffset: finalOffset, + isBackward: false + }) + }); +}; + +var insertFragmentIntoContentState = function insertFragmentIntoContentState(contentState, selectionState, fragmentBlockMap) { + !selectionState.isCollapsed() ? process.env.NODE_ENV !== 'production' ? invariant(false, '`insertFragment` should only be called with a collapsed selection state.') : invariant(false) : void 0; + + var blockMap = contentState.getBlockMap(); + var fragment = randomizeBlockMapKeys(fragmentBlockMap); + var targetKey = selectionState.getStartKey(); + var targetOffset = selectionState.getStartOffset(); + + var targetBlock = blockMap.get(targetKey); + + if (targetBlock instanceof ContentBlockNode) { + !targetBlock.getChildKeys().isEmpty() ? process.env.NODE_ENV !== 'production' ? invariant(false, '`insertFragment` should not be called when a container node is selected.') : invariant(false) : void 0; + } + + // When we insert a fragment with a single block we simply update the target block + // with the contents of the inserted fragment block + if (fragment.size === 1) { + return updateExistingBlock(contentState, selectionState, blockMap, fragment.first(), targetKey, targetOffset); + } + + return insertFragment(contentState, selectionState, blockMap, fragment, targetKey, targetOffset); +}; + +module.exports = insertFragmentIntoContentState; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 146 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule insertTextIntoContentState + * @format + * + */ + + + +var Immutable = __webpack_require__(1); + +var insertIntoList = __webpack_require__(67); +var invariant = __webpack_require__(2); + +var Repeat = Immutable.Repeat; + + +function insertTextIntoContentState(contentState, selectionState, text, characterMetadata) { + !selectionState.isCollapsed() ? process.env.NODE_ENV !== 'production' ? invariant(false, '`insertText` should only be called with a collapsed range.') : invariant(false) : void 0; + + var len = text.length; + if (!len) { + return contentState; + } + + var blockMap = contentState.getBlockMap(); + var key = selectionState.getStartKey(); + var offset = selectionState.getStartOffset(); + var block = blockMap.get(key); + var blockText = block.getText(); + + var newBlock = block.merge({ + text: blockText.slice(0, offset) + text + blockText.slice(offset, block.getLength()), + characterList: insertIntoList(block.getCharacterList(), Repeat(characterMetadata, len).toList(), offset) + }); + + var newOffset = offset + len; + + return contentState.merge({ + blockMap: blockMap.set(key, newBlock), + selectionAfter: selectionState.merge({ + anchorOffset: newOffset, + focusOffset: newOffset + }) + }); +} + +module.exports = insertTextIntoContentState; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 147 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyCommandBackspaceToStartOfLine + * @format + * + */ + + + +var EditorState = __webpack_require__(3); + +var expandRangeToStartOfLine = __webpack_require__(139); +var getDraftEditorSelectionWithNodes = __webpack_require__(59); +var moveSelectionBackward = __webpack_require__(34); +var removeTextWithStrategy = __webpack_require__(23); + +function keyCommandBackspaceToStartOfLine(editorState) { + var afterRemoval = removeTextWithStrategy(editorState, function (strategyState) { + var selection = strategyState.getSelection(); + if (selection.isCollapsed() && selection.getAnchorOffset() === 0) { + return moveSelectionBackward(strategyState, 1); + } + + var domSelection = global.getSelection(); + var range = domSelection.getRangeAt(0); + range = expandRangeToStartOfLine(range); + + return getDraftEditorSelectionWithNodes(strategyState, null, range.endContainer, range.endOffset, range.startContainer, range.startOffset).selectionState; + }, 'backward'); + + if (afterRemoval === editorState.getCurrentContent()) { + return editorState; + } + + return EditorState.push(editorState, afterRemoval, 'remove-range'); +} + +module.exports = keyCommandBackspaceToStartOfLine; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) + +/***/ }), +/* 148 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyCommandBackspaceWord + * @format + * + */ + + + +var DraftRemovableWord = __webpack_require__(54); +var EditorState = __webpack_require__(3); + +var moveSelectionBackward = __webpack_require__(34); +var removeTextWithStrategy = __webpack_require__(23); + +/** + * Delete the word that is left of the cursor, as well as any spaces or + * punctuation after the word. + */ +function keyCommandBackspaceWord(editorState) { + var afterRemoval = removeTextWithStrategy(editorState, function (strategyState) { + var selection = strategyState.getSelection(); + var offset = selection.getStartOffset(); + // If there are no words before the cursor, remove the preceding newline. + if (offset === 0) { + return moveSelectionBackward(strategyState, 1); + } + var key = selection.getStartKey(); + var content = strategyState.getCurrentContent(); + var text = content.getBlockForKey(key).getText().slice(0, offset); + var toRemove = DraftRemovableWord.getBackward(text); + return moveSelectionBackward(strategyState, toRemove.length || 1); + }, 'backward'); + + if (afterRemoval === editorState.getCurrentContent()) { + return editorState; + } + + return EditorState.push(editorState, afterRemoval, 'remove-range'); +} + +module.exports = keyCommandBackspaceWord; + +/***/ }), +/* 149 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyCommandDeleteWord + * @format + * + */ + + + +var DraftRemovableWord = __webpack_require__(54); +var EditorState = __webpack_require__(3); + +var moveSelectionForward = __webpack_require__(69); +var removeTextWithStrategy = __webpack_require__(23); + +/** + * Delete the word that is right of the cursor, as well as any spaces or + * punctuation before the word. + */ +function keyCommandDeleteWord(editorState) { + var afterRemoval = removeTextWithStrategy(editorState, function (strategyState) { + var selection = strategyState.getSelection(); + var offset = selection.getStartOffset(); + var key = selection.getStartKey(); + var content = strategyState.getCurrentContent(); + var text = content.getBlockForKey(key).getText().slice(offset); + var toRemove = DraftRemovableWord.getForward(text); + + // If there are no words in front of the cursor, remove the newline. + return moveSelectionForward(strategyState, toRemove.length || 1); + }, 'forward'); + + if (afterRemoval === editorState.getCurrentContent()) { + return editorState; + } + + return EditorState.push(editorState, afterRemoval, 'remove-range'); +} + +module.exports = keyCommandDeleteWord; + +/***/ }), +/* 150 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyCommandInsertNewline + * @format + * + */ + + + +var DraftModifier = __webpack_require__(6); +var EditorState = __webpack_require__(3); + +function keyCommandInsertNewline(editorState) { + var contentState = DraftModifier.splitBlock(editorState.getCurrentContent(), editorState.getSelection()); + return EditorState.push(editorState, contentState, 'split-block'); +} + +module.exports = keyCommandInsertNewline; + +/***/ }), +/* 151 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyCommandMoveSelectionToEndOfBlock + * @format + * + */ + + + +var EditorState = __webpack_require__(3); + +/** + * See comment for `moveSelectionToStartOfBlock`. + */ +function keyCommandMoveSelectionToEndOfBlock(editorState) { + var selection = editorState.getSelection(); + var endKey = selection.getEndKey(); + var content = editorState.getCurrentContent(); + var textLength = content.getBlockForKey(endKey).getLength(); + return EditorState.set(editorState, { + selection: selection.merge({ + anchorKey: endKey, + anchorOffset: textLength, + focusKey: endKey, + focusOffset: textLength, + isBackward: false + }), + forceSelection: true + }); +} + +module.exports = keyCommandMoveSelectionToEndOfBlock; + +/***/ }), +/* 152 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyCommandMoveSelectionToStartOfBlock + * @format + * + */ + + + +var EditorState = __webpack_require__(3); + +/** + * Collapse selection at the start of the first selected block. This is used + * for Firefox versions that attempt to navigate forward/backward instead of + * moving the cursor. Other browsers are able to move the cursor natively. + */ +function keyCommandMoveSelectionToStartOfBlock(editorState) { + var selection = editorState.getSelection(); + var startKey = selection.getStartKey(); + return EditorState.set(editorState, { + selection: selection.merge({ + anchorKey: startKey, + anchorOffset: 0, + focusKey: startKey, + focusOffset: 0, + isBackward: false + }), + forceSelection: true + }); +} + +module.exports = keyCommandMoveSelectionToStartOfBlock; + +/***/ }), +/* 153 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyCommandPlainBackspace + * @format + * + */ + + + +var EditorState = __webpack_require__(3); +var UnicodeUtils = __webpack_require__(16); + +var moveSelectionBackward = __webpack_require__(34); +var removeTextWithStrategy = __webpack_require__(23); + +/** + * Remove the selected range. If the cursor is collapsed, remove the preceding + * character. This operation is Unicode-aware, so removing a single character + * will remove a surrogate pair properly as well. + */ +function keyCommandPlainBackspace(editorState) { + var afterRemoval = removeTextWithStrategy(editorState, function (strategyState) { + var selection = strategyState.getSelection(); + var content = strategyState.getCurrentContent(); + var key = selection.getAnchorKey(); + var offset = selection.getAnchorOffset(); + var charBehind = content.getBlockForKey(key).getText()[offset - 1]; + return moveSelectionBackward(strategyState, charBehind ? UnicodeUtils.getUTF16Length(charBehind, 0) : 1); + }, 'backward'); + + if (afterRemoval === editorState.getCurrentContent()) { + return editorState; + } + + var selection = editorState.getSelection(); + return EditorState.push(editorState, afterRemoval.set('selectionBefore', selection), selection.isCollapsed() ? 'backspace-character' : 'remove-range'); +} + +module.exports = keyCommandPlainBackspace; + +/***/ }), +/* 154 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyCommandPlainDelete + * @format + * + */ + + + +var EditorState = __webpack_require__(3); +var UnicodeUtils = __webpack_require__(16); + +var moveSelectionForward = __webpack_require__(69); +var removeTextWithStrategy = __webpack_require__(23); + +/** + * Remove the selected range. If the cursor is collapsed, remove the following + * character. This operation is Unicode-aware, so removing a single character + * will remove a surrogate pair properly as well. + */ +function keyCommandPlainDelete(editorState) { + var afterRemoval = removeTextWithStrategy(editorState, function (strategyState) { + var selection = strategyState.getSelection(); + var content = strategyState.getCurrentContent(); + var key = selection.getAnchorKey(); + var offset = selection.getAnchorOffset(); + var charAhead = content.getBlockForKey(key).getText()[offset]; + return moveSelectionForward(strategyState, charAhead ? UnicodeUtils.getUTF16Length(charAhead, 0) : 1); + }, 'forward'); + + if (afterRemoval === editorState.getCurrentContent()) { + return editorState; + } + + var selection = editorState.getSelection(); + + return EditorState.push(editorState, afterRemoval.set('selectionBefore', selection), selection.isCollapsed() ? 'delete-character' : 'remove-range'); +} + +module.exports = keyCommandPlainDelete; + +/***/ }), +/* 155 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyCommandTransposeCharacters + * @format + * + */ + + + +var DraftModifier = __webpack_require__(6); +var EditorState = __webpack_require__(3); + +var getContentStateFragment = __webpack_require__(27); + +/** + * Transpose the characters on either side of a collapsed cursor, or + * if the cursor is at the end of the block, transpose the last two + * characters. + */ +function keyCommandTransposeCharacters(editorState) { + var selection = editorState.getSelection(); + if (!selection.isCollapsed()) { + return editorState; + } + + var offset = selection.getAnchorOffset(); + if (offset === 0) { + return editorState; + } + + var blockKey = selection.getAnchorKey(); + var content = editorState.getCurrentContent(); + var block = content.getBlockForKey(blockKey); + var length = block.getLength(); + + // Nothing to transpose if there aren't two characters. + if (length <= 1) { + return editorState; + } + + var removalRange; + var finalSelection; + + if (offset === length) { + // The cursor is at the end of the block. Swap the last two characters. + removalRange = selection.set('anchorOffset', offset - 1); + finalSelection = selection; + } else { + removalRange = selection.set('focusOffset', offset + 1); + finalSelection = removalRange.set('anchorOffset', offset + 1); + } + + // Extract the character to move as a fragment. This preserves its + // styling and entity, if any. + var movedFragment = getContentStateFragment(content, removalRange); + var afterRemoval = DraftModifier.removeRange(content, removalRange, 'backward'); + + // After the removal, the insertion target is one character back. + var selectionAfter = afterRemoval.getSelectionAfter(); + var targetOffset = selectionAfter.getAnchorOffset() - 1; + var targetRange = selectionAfter.merge({ + anchorOffset: targetOffset, + focusOffset: targetOffset + }); + + var afterInsert = DraftModifier.replaceWithFragment(afterRemoval, targetRange, movedFragment); + + var newEditorState = EditorState.push(editorState, afterInsert, 'insert-fragment'); + + return EditorState.acceptSelection(newEditorState, finalSelection); +} + +module.exports = keyCommandTransposeCharacters; + +/***/ }), +/* 156 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule keyCommandUndo + * @format + * + */ + + + +var EditorState = __webpack_require__(3); + +function keyCommandUndo(e, editorState, updateFn) { + var undoneState = EditorState.undo(editorState); + + // If the last change to occur was a spellcheck change, allow the undo + // event to fall through to the browser. This allows the browser to record + // the unwanted change, which should soon lead it to learn not to suggest + // the correction again. + if (editorState.getLastChangeType() === 'spellcheck-change') { + var nativelyRenderedContent = undoneState.getCurrentContent(); + updateFn(EditorState.set(undoneState, { nativelyRenderedContent: nativelyRenderedContent })); + return; + } + + // Otheriwse, manage the undo behavior manually. + e.preventDefault(); + if (!editorState.getNativelyRenderedContent()) { + updateFn(undoneState); + return; + } + + // Trigger a re-render with the current content state to ensure that the + // component tree has up-to-date props for comparison. + updateFn(EditorState.set(editorState, { nativelyRenderedContent: null })); + + // Wait to ensure that the re-render has occurred before performing + // the undo action. + setTimeout(function () { + updateFn(undoneState); + }, 0); +} + +module.exports = keyCommandUndo; + +/***/ }), +/* 157 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule modifyBlockForContentState + * @format + * + */ + + + +var Immutable = __webpack_require__(1); + +var Map = Immutable.Map; + + +function modifyBlockForContentState(contentState, selectionState, operation) { + var startKey = selectionState.getStartKey(); + var endKey = selectionState.getEndKey(); + var blockMap = contentState.getBlockMap(); + var newBlocks = blockMap.toSeq().skipUntil(function (_, k) { + return k === startKey; + }).takeUntil(function (_, k) { + return k === endKey; + }).concat(Map([[endKey, blockMap.get(endKey)]])).map(operation); + + return contentState.merge({ + blockMap: blockMap.merge(newBlocks), + selectionBefore: selectionState, + selectionAfter: selectionState + }); +} + +module.exports = modifyBlockForContentState; + +/***/ }), +/* 158 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule moveBlockInContentState + * @format + * + */ + + + +var ContentBlockNode = __webpack_require__(9); +var Immutable = __webpack_require__(1); + +var getNextDelimiterBlockKey = __webpack_require__(61); +var invariant = __webpack_require__(2); + +var OrderedMap = Immutable.OrderedMap, + List = Immutable.List; + + +var transformBlock = function transformBlock(key, blockMap, func) { + if (!key) { + return; + } + + var block = blockMap.get(key); + + if (!block) { + return; + } + + blockMap.set(key, func(block)); +}; + +var updateBlockMapLinks = function updateBlockMapLinks(blockMap, originalBlockToBeMoved, originalTargetBlock, insertionMode, isExperimentalTreeBlock) { + if (!isExperimentalTreeBlock) { + return blockMap; + } + // possible values of 'insertionMode' are: 'after', 'before' + var isInsertedAfterTarget = insertionMode === 'after'; + + var originalBlockKey = originalBlockToBeMoved.getKey(); + var originalTargetKey = originalTargetBlock.getKey(); + var originalParentKey = originalBlockToBeMoved.getParentKey(); + var originalNextSiblingKey = originalBlockToBeMoved.getNextSiblingKey(); + var originalPrevSiblingKey = originalBlockToBeMoved.getPrevSiblingKey(); + var newParentKey = originalTargetBlock.getParentKey(); + var newNextSiblingKey = isInsertedAfterTarget ? originalTargetBlock.getNextSiblingKey() : originalTargetKey; + var newPrevSiblingKey = isInsertedAfterTarget ? originalTargetKey : originalTargetBlock.getPrevSiblingKey(); + + return blockMap.withMutations(function (blocks) { + // update old parent + transformBlock(originalParentKey, blocks, function (block) { + var parentChildrenList = block.getChildKeys(); + return block.merge({ + children: parentChildrenList['delete'](parentChildrenList.indexOf(originalBlockKey)) + }); + }); + + // update old prev + transformBlock(originalPrevSiblingKey, blocks, function (block) { + return block.merge({ + nextSibling: originalNextSiblingKey + }); + }); + + // update old next + transformBlock(originalNextSiblingKey, blocks, function (block) { + return block.merge({ + prevSibling: originalPrevSiblingKey + }); + }); + + // update new next + transformBlock(newNextSiblingKey, blocks, function (block) { + return block.merge({ + prevSibling: originalBlockKey + }); + }); + + // update new prev + transformBlock(newPrevSiblingKey, blocks, function (block) { + return block.merge({ + nextSibling: originalBlockKey + }); + }); + + // update new parent + transformBlock(newParentKey, blocks, function (block) { + var newParentChildrenList = block.getChildKeys(); + var targetBlockIndex = newParentChildrenList.indexOf(originalTargetKey); + + var insertionIndex = isInsertedAfterTarget ? targetBlockIndex + 1 : targetBlockIndex !== 0 ? targetBlockIndex - 1 : 0; + + var newChildrenArray = newParentChildrenList.toArray(); + newChildrenArray.splice(insertionIndex, 0, originalBlockKey); + + return block.merge({ + children: List(newChildrenArray) + }); + }); + + // update block + transformBlock(originalBlockKey, blocks, function (block) { + return block.merge({ + nextSibling: newNextSiblingKey, + prevSibling: newPrevSiblingKey, + parent: newParentKey + }); + }); + }); +}; + +var moveBlockInContentState = function moveBlockInContentState(contentState, blockToBeMoved, targetBlock, insertionMode) { + !(insertionMode !== 'replace') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Replacing blocks is not supported.') : invariant(false) : void 0; + + var targetKey = targetBlock.getKey(); + var blockKey = blockToBeMoved.getKey(); + + !(blockKey !== targetKey) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Block cannot be moved next to itself.') : invariant(false) : void 0; + + var blockMap = contentState.getBlockMap(); + var isExperimentalTreeBlock = blockToBeMoved instanceof ContentBlockNode; + + var blocksToBeMoved = [blockToBeMoved]; + var blockMapWithoutBlocksToBeMoved = blockMap['delete'](blockKey); + + if (isExperimentalTreeBlock) { + blocksToBeMoved = []; + blockMapWithoutBlocksToBeMoved = blockMap.withMutations(function (blocks) { + var nextSiblingKey = blockToBeMoved.getNextSiblingKey(); + var nextDelimiterBlockKey = getNextDelimiterBlockKey(blockToBeMoved, blocks); + + blocks.toSeq().skipUntil(function (block) { + return block.getKey() === blockKey; + }).takeWhile(function (block) { + var key = block.getKey(); + var isBlockToBeMoved = key === blockKey; + var hasNextSiblingAndIsNotNextSibling = nextSiblingKey && key !== nextSiblingKey; + var doesNotHaveNextSiblingAndIsNotDelimiter = !nextSiblingKey && block.getParentKey() && (!nextDelimiterBlockKey || key !== nextDelimiterBlockKey); + + return !!(isBlockToBeMoved || hasNextSiblingAndIsNotNextSibling || doesNotHaveNextSiblingAndIsNotDelimiter); + }).forEach(function (block) { + blocksToBeMoved.push(block); + blocks['delete'](block.getKey()); + }); + }); + } + + var blocksBefore = blockMapWithoutBlocksToBeMoved.toSeq().takeUntil(function (v) { + return v === targetBlock; + }); + + var blocksAfter = blockMapWithoutBlocksToBeMoved.toSeq().skipUntil(function (v) { + return v === targetBlock; + }).skip(1); + + var slicedBlocks = blocksToBeMoved.map(function (block) { + return [block.getKey(), block]; + }); + + var newBlocks = OrderedMap(); + + if (insertionMode === 'before') { + var blockBefore = contentState.getBlockBefore(targetKey); + + !(!blockBefore || blockBefore.getKey() !== blockToBeMoved.getKey()) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Block cannot be moved next to itself.') : invariant(false) : void 0; + + newBlocks = blocksBefore.concat([].concat(slicedBlocks, [[targetKey, targetBlock]]), blocksAfter).toOrderedMap(); + } else if (insertionMode === 'after') { + var blockAfter = contentState.getBlockAfter(targetKey); + + !(!blockAfter || blockAfter.getKey() !== blockKey) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Block cannot be moved next to itself.') : invariant(false) : void 0; + + newBlocks = blocksBefore.concat([[targetKey, targetBlock]].concat(slicedBlocks), blocksAfter).toOrderedMap(); + } + + return contentState.merge({ + blockMap: updateBlockMapLinks(newBlocks, blockToBeMoved, targetBlock, insertionMode, isExperimentalTreeBlock), + selectionBefore: contentState.getSelectionAfter(), + selectionAfter: contentState.getSelectionAfter().merge({ + anchorKey: blockKey, + focusKey: blockKey + }) + }); +}; + +module.exports = moveBlockInContentState; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 159 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule removeRangeFromContentState + * @format + * + */ + + + +var ContentBlockNode = __webpack_require__(9); +var Immutable = __webpack_require__(1); + +var getNextDelimiterBlockKey = __webpack_require__(61); + +var List = Immutable.List, + Map = Immutable.Map; + + +var transformBlock = function transformBlock(key, blockMap, func) { + if (!key) { + return; + } + + var block = blockMap.get(key); + + if (!block) { + return; + } + + blockMap.set(key, func(block)); +}; + +/** + * Ancestors needs to be preserved when there are non selected + * children to make sure we do not leave any orphans behind + */ +var getAncestorsKeys = function getAncestorsKeys(blockKey, blockMap) { + var parents = []; + + if (!blockKey) { + return parents; + } + + var blockNode = blockMap.get(blockKey); + while (blockNode && blockNode.getParentKey()) { + var parentKey = blockNode.getParentKey(); + if (parentKey) { + parents.push(parentKey); + } + blockNode = parentKey ? blockMap.get(parentKey) : null; + } + + return parents; +}; + +/** + * Get all next delimiter keys until we hit a root delimiter and return + * an array of key references + */ +var getNextDelimitersBlockKeys = function getNextDelimitersBlockKeys(block, blockMap) { + var nextDelimiters = []; + + if (!block) { + return nextDelimiters; + } + + var nextDelimiter = getNextDelimiterBlockKey(block, blockMap); + while (nextDelimiter && blockMap.get(nextDelimiter)) { + var _block = blockMap.get(nextDelimiter); + nextDelimiters.push(nextDelimiter); + + // we do not need to keep checking all root node siblings, just the first occurance + nextDelimiter = _block.getParentKey() ? getNextDelimiterBlockKey(_block, blockMap) : null; + } + + return nextDelimiters; +}; + +var getNextValidSibling = function getNextValidSibling(block, blockMap, originalBlockMap) { + if (!block) { + return null; + } + + // note that we need to make sure we refer to the original block since this + // function is called within a withMutations + var nextValidSiblingKey = originalBlockMap.get(block.getKey()).getNextSiblingKey(); + + while (nextValidSiblingKey && !blockMap.get(nextValidSiblingKey)) { + nextValidSiblingKey = originalBlockMap.get(nextValidSiblingKey).getNextSiblingKey() || null; + } + + return nextValidSiblingKey; +}; + +var getPrevValidSibling = function getPrevValidSibling(block, blockMap, originalBlockMap) { + if (!block) { + return null; + } + + // note that we need to make sure we refer to the original block since this + // function is called within a withMutations + var prevValidSiblingKey = originalBlockMap.get(block.getKey()).getPrevSiblingKey(); + + while (prevValidSiblingKey && !blockMap.get(prevValidSiblingKey)) { + prevValidSiblingKey = originalBlockMap.get(prevValidSiblingKey).getPrevSiblingKey() || null; + } + + return prevValidSiblingKey; +}; + +var updateBlockMapLinks = function updateBlockMapLinks(blockMap, startBlock, endBlock, originalBlockMap) { + return blockMap.withMutations(function (blocks) { + // update start block if its retained + transformBlock(startBlock.getKey(), blocks, function (block) { + return block.merge({ + nextSibling: getNextValidSibling(startBlock, blocks, originalBlockMap), + prevSibling: getPrevValidSibling(startBlock, blocks, originalBlockMap) + }); + }); + + // update endblock if its retained + transformBlock(endBlock.getKey(), blocks, function (block) { + return block.merge({ + nextSibling: getNextValidSibling(endBlock, blocks, originalBlockMap), + prevSibling: getPrevValidSibling(endBlock, blocks, originalBlockMap) + }); + }); + + // update start block parent ancestors + getAncestorsKeys(startBlock.getKey(), originalBlockMap).forEach(function (parentKey) { + return transformBlock(parentKey, blocks, function (block) { + return block.merge({ + children: block.getChildKeys().filter(function (key) { + return blocks.get(key); + }), + nextSibling: getNextValidSibling(block, blocks, originalBlockMap), + prevSibling: getPrevValidSibling(block, blocks, originalBlockMap) + }); + }); + }); + + // update start block next - can only happen if startBlock == endBlock + transformBlock(startBlock.getNextSiblingKey(), blocks, function (block) { + return block.merge({ + prevSibling: startBlock.getPrevSiblingKey() + }); + }); + + // update start block prev + transformBlock(startBlock.getPrevSiblingKey(), blocks, function (block) { + return block.merge({ + nextSibling: getNextValidSibling(startBlock, blocks, originalBlockMap) + }); + }); + + // update end block next + transformBlock(endBlock.getNextSiblingKey(), blocks, function (block) { + return block.merge({ + prevSibling: getPrevValidSibling(endBlock, blocks, originalBlockMap) + }); + }); + + // update end block prev + transformBlock(endBlock.getPrevSiblingKey(), blocks, function (block) { + return block.merge({ + nextSibling: endBlock.getNextSiblingKey() + }); + }); + + // update end block parent ancestors + getAncestorsKeys(endBlock.getKey(), originalBlockMap).forEach(function (parentKey) { + transformBlock(parentKey, blocks, function (block) { + return block.merge({ + children: block.getChildKeys().filter(function (key) { + return blocks.get(key); + }), + nextSibling: getNextValidSibling(block, blocks, originalBlockMap), + prevSibling: getPrevValidSibling(block, blocks, originalBlockMap) + }); + }); + }); + + // update next delimiters all the way to a root delimiter + getNextDelimitersBlockKeys(endBlock, originalBlockMap).forEach(function (delimiterKey) { + return transformBlock(delimiterKey, blocks, function (block) { + return block.merge({ + nextSibling: getNextValidSibling(block, blocks, originalBlockMap), + prevSibling: getPrevValidSibling(block, blocks, originalBlockMap) + }); + }); + }); + }); +}; + +var removeRangeFromContentState = function removeRangeFromContentState(contentState, selectionState) { + if (selectionState.isCollapsed()) { + return contentState; + } + + var blockMap = contentState.getBlockMap(); + var startKey = selectionState.getStartKey(); + var startOffset = selectionState.getStartOffset(); + var endKey = selectionState.getEndKey(); + var endOffset = selectionState.getEndOffset(); + + var startBlock = blockMap.get(startKey); + var endBlock = blockMap.get(endKey); + + // we assume that ContentBlockNode and ContentBlocks are not mixed together + var isExperimentalTreeBlock = startBlock instanceof ContentBlockNode; + + // used to retain blocks that should not be deleted to avoid orphan children + var parentAncestors = []; + + if (isExperimentalTreeBlock) { + var endBlockchildrenKeys = endBlock.getChildKeys(); + var endBlockAncestors = getAncestorsKeys(endKey, blockMap); + + // endBlock has unselected sibblings so we can not remove its ancestors parents + if (endBlock.getNextSiblingKey()) { + parentAncestors = parentAncestors.concat(endBlockAncestors); + } + + // endBlock has children so can not remove this block or any of its ancestors + if (!endBlockchildrenKeys.isEmpty()) { + parentAncestors = parentAncestors.concat(endBlockAncestors.concat([endKey])); + } + + // we need to retain all ancestors of the next delimiter block + parentAncestors = parentAncestors.concat(getAncestorsKeys(getNextDelimiterBlockKey(endBlock, blockMap), blockMap)); + } + + var characterList = void 0; + + if (startBlock === endBlock) { + characterList = removeFromList(startBlock.getCharacterList(), startOffset, endOffset); + } else { + characterList = startBlock.getCharacterList().slice(0, startOffset).concat(endBlock.getCharacterList().slice(endOffset)); + } + + var modifiedStart = startBlock.merge({ + text: startBlock.getText().slice(0, startOffset) + endBlock.getText().slice(endOffset), + characterList: characterList + }); + + var newBlocks = blockMap.toSeq().skipUntil(function (_, k) { + return k === startKey; + }).takeUntil(function (_, k) { + return k === endKey; + }).filter(function (_, k) { + return parentAncestors.indexOf(k) === -1; + }).concat(Map([[endKey, null]])).map(function (_, k) { + return k === startKey ? modifiedStart : null; + }); + + var updatedBlockMap = blockMap.merge(newBlocks).filter(function (block) { + return !!block; + }); + + if (isExperimentalTreeBlock) { + updatedBlockMap = updateBlockMapLinks(updatedBlockMap, startBlock, endBlock, blockMap); + } + + return contentState.merge({ + blockMap: updatedBlockMap, + selectionBefore: selectionState, + selectionAfter: selectionState.merge({ + anchorKey: startKey, + anchorOffset: startOffset, + focusKey: startKey, + focusOffset: startOffset, + isBackward: false + }) + }); +}; + +/** + * Maintain persistence for target list when removing characters on the + * head and tail of the character list. + */ +var removeFromList = function removeFromList(targetList, startOffset, endOffset) { + if (startOffset === 0) { + while (startOffset < endOffset) { + targetList = targetList.shift(); + startOffset++; + } + } else if (endOffset === targetList.count()) { + while (endOffset > startOffset) { + targetList = targetList.pop(); + endOffset--; + } + } else { + var head = targetList.slice(0, startOffset); + var tail = targetList.slice(endOffset); + targetList = head.concat(tail).toList(); + } + return targetList; +}; + +module.exports = removeRangeFromContentState; + +/***/ }), +/* 160 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process, global) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule setDraftEditorSelection + * @format + * + */ + + + +var DraftJsDebugLogging = __webpack_require__(112); + +var containsNode = __webpack_require__(39); +var getActiveElement = __webpack_require__(75); +var invariant = __webpack_require__(2); + +function getAnonymizedDOM(node, getNodeLabels) { + if (!node) { + return '[empty]'; + } + + var anonymized = anonymizeTextWithin(node, getNodeLabels); + if (anonymized.nodeType === Node.TEXT_NODE) { + return anonymized.textContent; + } + + !(anonymized instanceof Element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Node must be an Element if it is not a text node.') : invariant(false) : void 0; + return anonymized.outerHTML; +} + +function anonymizeTextWithin(node, getNodeLabels) { + var labels = getNodeLabels !== undefined ? getNodeLabels(node) : []; + + if (node.nodeType === Node.TEXT_NODE) { + var length = node.textContent.length; + return document.createTextNode('[text ' + length + (labels.length ? ' | ' + labels.join(', ') : '') + ']'); + } + + var clone = node.cloneNode(); + if (clone.nodeType === 1 && labels.length) { + clone.setAttribute('data-labels', labels.join(', ')); + } + var childNodes = node.childNodes; + for (var ii = 0; ii < childNodes.length; ii++) { + clone.appendChild(anonymizeTextWithin(childNodes[ii], getNodeLabels)); + } + + return clone; +} + +function getAnonymizedEditorDOM(node, getNodeLabels) { + // grabbing the DOM content of the Draft editor + var currentNode = node; + while (currentNode) { + if (currentNode instanceof Element && currentNode.hasAttribute('contenteditable')) { + // found the Draft editor container + return getAnonymizedDOM(currentNode, getNodeLabels); + } else { + currentNode = currentNode.parentNode; + } + } + return 'Could not find contentEditable parent of node'; +} + +function getNodeLength(node) { + return node.nodeValue === null ? node.childNodes.length : node.nodeValue.length; +} + +/** + * In modern non-IE browsers, we can support both forward and backward + * selections. + * + * Note: IE10+ supports the Selection object, but it does not support + * the `extend` method, which means that even in modern IE, it's not possible + * to programatically create a backward selection. Thus, for all IE + * versions, we use the old IE API to create our selections. + */ +function setDraftEditorSelection(selectionState, node, blockKey, nodeStart, nodeEnd) { + // It's possible that the editor has been removed from the DOM but + // our selection code doesn't know it yet. Forcing selection in + // this case may lead to errors, so just bail now. + if (!containsNode(document.documentElement, node)) { + return; + } + + var selection = global.getSelection(); + var anchorKey = selectionState.getAnchorKey(); + var anchorOffset = selectionState.getAnchorOffset(); + var focusKey = selectionState.getFocusKey(); + var focusOffset = selectionState.getFocusOffset(); + var isBackward = selectionState.getIsBackward(); + + // IE doesn't support backward selection. Swap key/offset pairs. + if (!selection.extend && isBackward) { + var tempKey = anchorKey; + var tempOffset = anchorOffset; + anchorKey = focusKey; + anchorOffset = focusOffset; + focusKey = tempKey; + focusOffset = tempOffset; + isBackward = false; + } + + var hasAnchor = anchorKey === blockKey && nodeStart <= anchorOffset && nodeEnd >= anchorOffset; + + var hasFocus = focusKey === blockKey && nodeStart <= focusOffset && nodeEnd >= focusOffset; + + // If the selection is entirely bound within this node, set the selection + // and be done. + if (hasAnchor && hasFocus) { + selection.removeAllRanges(); + addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState); + addFocusToSelection(selection, node, focusOffset - nodeStart, selectionState); + return; + } + + if (!isBackward) { + // If the anchor is within this node, set the range start. + if (hasAnchor) { + selection.removeAllRanges(); + addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState); + } + + // If the focus is within this node, we can assume that we have + // already set the appropriate start range on the selection, and + // can simply extend the selection. + if (hasFocus) { + addFocusToSelection(selection, node, focusOffset - nodeStart, selectionState); + } + } else { + // If this node has the focus, set the selection range to be a + // collapsed range beginning here. Later, when we encounter the anchor, + // we'll use this information to extend the selection. + if (hasFocus) { + selection.removeAllRanges(); + addPointToSelection(selection, node, focusOffset - nodeStart, selectionState); + } + + // If this node has the anchor, we may assume that the correct + // focus information is already stored on the selection object. + // We keep track of it, reset the selection range, and extend it + // back to the focus point. + if (hasAnchor) { + var storedFocusNode = selection.focusNode; + var storedFocusOffset = selection.focusOffset; + + selection.removeAllRanges(); + addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState); + addFocusToSelection(selection, storedFocusNode, storedFocusOffset, selectionState); + } + } +} + +/** + * Extend selection towards focus point. + */ +function addFocusToSelection(selection, node, offset, selectionState) { + var activeElement = getActiveElement(); + if (selection.extend && containsNode(activeElement, node)) { + // If `extend` is called while another element has focus, an error is + // thrown. We therefore disable `extend` if the active element is somewhere + // other than the node we are selecting. This should only occur in Firefox, + // since it is the only browser to support multiple selections. + // See https://bugzilla.mozilla.org/show_bug.cgi?id=921444. + + // logging to catch bug that is being reported in t16250795 + if (offset > getNodeLength(node)) { + // the call to 'selection.extend' is about to throw + DraftJsDebugLogging.logSelectionStateFailure({ + anonymizedDom: getAnonymizedEditorDOM(node), + extraParams: JSON.stringify({ offset: offset }), + selectionState: JSON.stringify(selectionState.toJS()) + }); + } + + // logging to catch bug that is being reported in t18110632 + var nodeWasFocus = node === selection.focusNode; + try { + selection.extend(node, offset); + } catch (e) { + DraftJsDebugLogging.logSelectionStateFailure({ + anonymizedDom: getAnonymizedEditorDOM(node, function (n) { + var labels = []; + if (n === activeElement) { + labels.push('active element'); + } + if (n === selection.anchorNode) { + labels.push('selection anchor node'); + } + if (n === selection.focusNode) { + labels.push('selection focus node'); + } + return labels; + }), + extraParams: JSON.stringify({ + activeElementName: activeElement ? activeElement.nodeName : null, + nodeIsFocus: node === selection.focusNode, + nodeWasFocus: nodeWasFocus, + selectionRangeCount: selection.rangeCount, + selectionAnchorNodeName: selection.anchorNode ? selection.anchorNode.nodeName : null, + selectionAnchorOffset: selection.anchorOffset, + selectionFocusNodeName: selection.focusNode ? selection.focusNode.nodeName : null, + selectionFocusOffset: selection.focusOffset, + message: e ? '' + e : null, + offset: offset + }, null, 2), + selectionState: JSON.stringify(selectionState.toJS(), null, 2) + }); + // allow the error to be thrown - + // better than continuing in a broken state + throw e; + } + } else { + // IE doesn't support extend. This will mean no backward selection. + // Extract the existing selection range and add focus to it. + // Additionally, clone the selection range. IE11 throws an + // InvalidStateError when attempting to access selection properties + // after the range is detached. + var range = selection.getRangeAt(0); + range.setEnd(node, offset); + selection.addRange(range.cloneRange()); + } +} + +function addPointToSelection(selection, node, offset, selectionState) { + var range = document.createRange(); + // logging to catch bug that is being reported in t16250795 + if (offset > getNodeLength(node)) { + // in this case we know that the call to 'range.setStart' is about to throw + DraftJsDebugLogging.logSelectionStateFailure({ + anonymizedDom: getAnonymizedEditorDOM(node), + extraParams: JSON.stringify({ offset: offset }), + selectionState: JSON.stringify(selectionState.toJS()) + }); + } + range.setStart(node, offset); + selection.addRange(range); +} + +module.exports = setDraftEditorSelection; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0), __webpack_require__(11))) + +/***/ }), +/* 161 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule splitBlockInContentState + * @format + * + */ + + + +var ContentBlockNode = __webpack_require__(9); +var Immutable = __webpack_require__(1); + +var generateRandomKey = __webpack_require__(13); +var invariant = __webpack_require__(2); + +var List = Immutable.List, + Map = Immutable.Map; + + +var transformBlock = function transformBlock(key, blockMap, func) { + if (!key) { + return; + } + + var block = blockMap.get(key); + + if (!block) { + return; + } + + blockMap.set(key, func(block)); +}; + +var updateBlockMapLinks = function updateBlockMapLinks(blockMap, originalBlock, belowBlock) { + return blockMap.withMutations(function (blocks) { + var originalBlockKey = originalBlock.getKey(); + var belowBlockKey = belowBlock.getKey(); + + // update block parent + transformBlock(originalBlock.getParentKey(), blocks, function (block) { + var parentChildrenList = block.getChildKeys(); + var insertionIndex = parentChildrenList.indexOf(originalBlockKey) + 1; + var newChildrenArray = parentChildrenList.toArray(); + + newChildrenArray.splice(insertionIndex, 0, belowBlockKey); + + return block.merge({ + children: List(newChildrenArray) + }); + }); + + // update original next block + transformBlock(originalBlock.getNextSiblingKey(), blocks, function (block) { + return block.merge({ + prevSibling: belowBlockKey + }); + }); + + // update original block + transformBlock(originalBlockKey, blocks, function (block) { + return block.merge({ + nextSibling: belowBlockKey + }); + }); + + // update below block + transformBlock(belowBlockKey, blocks, function (block) { + return block.merge({ + prevSibling: originalBlockKey + }); + }); + }); +}; + +var splitBlockInContentState = function splitBlockInContentState(contentState, selectionState) { + !selectionState.isCollapsed() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Selection range must be collapsed.') : invariant(false) : void 0; + + var key = selectionState.getAnchorKey(); + var offset = selectionState.getAnchorOffset(); + var blockMap = contentState.getBlockMap(); + var blockToSplit = blockMap.get(key); + var text = blockToSplit.getText(); + var chars = blockToSplit.getCharacterList(); + var keyBelow = generateRandomKey(); + var isExperimentalTreeBlock = blockToSplit instanceof ContentBlockNode; + + var blockAbove = blockToSplit.merge({ + text: text.slice(0, offset), + characterList: chars.slice(0, offset) + }); + var blockBelow = blockAbove.merge({ + key: keyBelow, + text: text.slice(offset), + characterList: chars.slice(offset), + data: Map() + }); + + var blocksBefore = blockMap.toSeq().takeUntil(function (v) { + return v === blockToSplit; + }); + var blocksAfter = blockMap.toSeq().skipUntil(function (v) { + return v === blockToSplit; + }).rest(); + var newBlocks = blocksBefore.concat([[key, blockAbove], [keyBelow, blockBelow]], blocksAfter).toOrderedMap(); + + if (isExperimentalTreeBlock) { + !blockToSplit.getChildKeys().isEmpty() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ContentBlockNode must not have children') : invariant(false) : void 0; + + newBlocks = updateBlockMapLinks(newBlocks, blockAbove, blockBelow); + } + + return contentState.merge({ + blockMap: newBlocks, + selectionBefore: selectionState, + selectionAfter: selectionState.merge({ + anchorKey: keyBelow, + anchorOffset: 0, + focusKey: keyBelow, + focusOffset: 0, + isBackward: false + }) + }); +}; + +module.exports = splitBlockInContentState; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 162 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule splitTextIntoTextBlocks + * @format + * + */ + + + +var NEWLINE_REGEX = /\r\n?|\n/g; + +function splitTextIntoTextBlocks(text) { + return text.split(NEWLINE_REGEX); +} + +module.exports = splitTextIntoTextBlocks; + +/***/ }), +/* 163 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +var PhotosMimeType = { + isImage: function isImage(mimeString) { + return getParts(mimeString)[0] === 'image'; + }, + isJpeg: function isJpeg(mimeString) { + var parts = getParts(mimeString); + return PhotosMimeType.isImage(mimeString) && ( + // see http://fburl.com/10972194 + parts[1] === 'jpeg' || parts[1] === 'pjpeg'); + } +}; + +function getParts(mimeString) { + return mimeString.split('/'); +} + +module.exports = PhotosMimeType; + +/***/ }), +/* 164 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + * @stub + * + */ + + + +// \u00a1-\u00b1\u00b4-\u00b8\u00ba\u00bb\u00bf +// is latin supplement punctuation except fractions and superscript +// numbers +// \u2010-\u2027\u2030-\u205e +// is punctuation from the general punctuation block: +// weird quotes, commas, bullets, dashes, etc. +// \u30fb\u3001\u3002\u3008-\u3011\u3014-\u301f +// is CJK punctuation +// \uff1a-\uff1f\uff01-\uff0f\uff3b-\uff40\uff5b-\uff65 +// is some full-width/half-width punctuation +// \u2E2E\u061f\u066a-\u066c\u061b\u060c\u060d\uFD3e\uFD3F +// is some Arabic punctuation marks +// \u1801\u0964\u104a\u104b +// is misc. other language punctuation marks + +var PUNCTUATION = '[.,+*?$|#{}()\'\\^\\-\\[\\]\\\\\\/!@%"~=<>_:;' + '\u30FB\u3001\u3002\u3008-\u3011\u3014-\u301F\uFF1A-\uFF1F\uFF01-\uFF0F' + '\uFF3B-\uFF40\uFF5B-\uFF65\u2E2E\u061F\u066A-\u066C\u061B\u060C\u060D' + '\uFD3E\uFD3F\u1801\u0964\u104A\u104B\u2010-\u2027\u2030-\u205E' + '\xA1-\xB1\xB4-\xB8\xBA\xBB\xBF]'; + +module.exports = { + getPunctuation: function getPunctuation() { + return PUNCTUATION; + } +}; + +/***/ }), +/* 165 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + */ + + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var URI = function () { + function URI(uri) { + _classCallCheck(this, URI); + + this._uri = uri; + } + + URI.prototype.toString = function toString() { + return this._uri; + }; + + return URI; +}(); + +module.exports = URI; + +/***/ }), +/* 166 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + * + */ + +/** + * Stateful API for text direction detection + * + * This class can be used in applications where you need to detect the + * direction of a sequence of text blocks, where each direction shall be used + * as the fallback direction for the next one. + * + * NOTE: A default direction, if not provided, is set based on the global + * direction, as defined by `UnicodeBidiDirection`. + * + * == Example == + * ``` + * var UnicodeBidiService = require('UnicodeBidiService'); + * + * var bidiService = new UnicodeBidiService(); + * + * ... + * + * bidiService.reset(); + * for (var para in paragraphs) { + * var dir = bidiService.getDirection(para); + * ... + * } + * ``` + * + * Part of our implementation of Unicode Bidirectional Algorithm (UBA) + * Unicode Standard Annex #9 (UAX9) + * http://www.unicode.org/reports/tr9/ + */ + + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var UnicodeBidi = __webpack_require__(74); +var UnicodeBidiDirection = __webpack_require__(38); + +var invariant = __webpack_require__(2); + +var UnicodeBidiService = function () { + + /** + * Stateful class for paragraph direction detection + * + * @param defaultDir Default direction of the service + */ + function UnicodeBidiService(defaultDir) { + _classCallCheck(this, UnicodeBidiService); + + if (!defaultDir) { + defaultDir = UnicodeBidiDirection.getGlobalDir(); + } else { + !UnicodeBidiDirection.isStrong(defaultDir) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Default direction must be a strong direction (LTR or RTL)') : invariant(false) : void 0; + } + this._defaultDir = defaultDir; + this.reset(); + } + + /** + * Reset the internal state + * + * Instead of creating a new instance, you can just reset() your instance + * everytime you start a new loop. + */ + + + UnicodeBidiService.prototype.reset = function reset() { + this._lastDir = this._defaultDir; + }; + + /** + * Returns the direction of a block of text, and remembers it as the + * fall-back direction for the next paragraph. + * + * @param str A text block, e.g. paragraph, table cell, tag + * @return The resolved direction + */ + + + UnicodeBidiService.prototype.getDirection = function getDirection(str) { + this._lastDir = UnicodeBidi.getDirection(str, this._lastDir); + return this._lastDir; + }; + + return UnicodeBidiService; +}(); + +module.exports = UnicodeBidiService; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 167 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/** + * Usage note: + * This module makes a best effort to export the same data we would internally. + * At Facebook we use a server-generated module that does the parsing and + * exports the data for the client to use. We can't rely on a server-side + * implementation in open source so instead we make use of an open source + * library to do the heavy lifting and then make some adjustments as necessary. + * It's likely there will be some differences. Some we can smooth over. + * Others are going to be harder. + */ + + + +var UAParser = __webpack_require__(211); + +var UNKNOWN = 'Unknown'; + +var PLATFORM_MAP = { + 'Mac OS': 'Mac OS X' +}; + +/** + * Convert from UAParser platform name to what we expect. + */ +function convertPlatformName(name) { + return PLATFORM_MAP[name] || name; +} + +/** + * Get the version number in parts. This is very naive. We actually get major + * version as a part of UAParser already, which is generally good enough, but + * let's get the minor just in case. + */ +function getBrowserVersion(version) { + if (!version) { + return { + major: '', + minor: '' + }; + } + var parts = version.split('.'); + return { + major: parts[0], + minor: parts[1] + }; +} + +/** + * Get the UA data fom UAParser and then convert it to the format we're + * expecting for our APIS. + */ +var parser = new UAParser(); +var results = parser.getResult(); + +// Do some conversion first. +var browserVersionData = getBrowserVersion(results.browser.version); +var uaData = { + browserArchitecture: results.cpu.architecture || UNKNOWN, + browserFullVersion: results.browser.version || UNKNOWN, + browserMinorVersion: browserVersionData.minor || UNKNOWN, + browserName: results.browser.name || UNKNOWN, + browserVersion: results.browser.major || UNKNOWN, + deviceName: results.device.model || UNKNOWN, + engineName: results.engine.name || UNKNOWN, + engineVersion: results.engine.version || UNKNOWN, + platformArchitecture: results.cpu.architecture || UNKNOWN, + platformName: convertPlatformName(results.os.name) || UNKNOWN, + platformVersion: results.os.version || UNKNOWN, + platformFullVersion: results.os.version || UNKNOWN +}; + +module.exports = uaData; + +/***/ }), +/* 168 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + + + +var invariant = __webpack_require__(2); + +var componentRegex = /\./; +var orRegex = /\|\|/; +var rangeRegex = /\s+\-\s+/; +var modifierRegex = /^(<=|<|=|>=|~>|~|>|)?\s*(.+)/; +var numericRegex = /^(\d*)(.*)/; + +/** + * Splits input `range` on "||" and returns true if any subrange matches + * `version`. + * + * @param {string} range + * @param {string} version + * @returns {boolean} + */ +function checkOrExpression(range, version) { + var expressions = range.split(orRegex); + + if (expressions.length > 1) { + return expressions.some(function (range) { + return VersionRange.contains(range, version); + }); + } else { + range = expressions[0].trim(); + return checkRangeExpression(range, version); + } +} + +/** + * Splits input `range` on " - " (the surrounding whitespace is required) and + * returns true if version falls between the two operands. + * + * @param {string} range + * @param {string} version + * @returns {boolean} + */ +function checkRangeExpression(range, version) { + var expressions = range.split(rangeRegex); + + !(expressions.length > 0 && expressions.length <= 2) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'the "-" operator expects exactly 2 operands') : invariant(false) : void 0; + + if (expressions.length === 1) { + return checkSimpleExpression(expressions[0], version); + } else { + var startVersion = expressions[0], + endVersion = expressions[1]; + + !(isSimpleVersion(startVersion) && isSimpleVersion(endVersion)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'operands to the "-" operator must be simple (no modifiers)') : invariant(false) : void 0; + + return checkSimpleExpression('>=' + startVersion, version) && checkSimpleExpression('<=' + endVersion, version); + } +} + +/** + * Checks if `range` matches `version`. `range` should be a "simple" range (ie. + * not a compound range using the " - " or "||" operators). + * + * @param {string} range + * @param {string} version + * @returns {boolean} + */ +function checkSimpleExpression(range, version) { + range = range.trim(); + if (range === '') { + return true; + } + + var versionComponents = version.split(componentRegex); + + var _getModifierAndCompon = getModifierAndComponents(range), + modifier = _getModifierAndCompon.modifier, + rangeComponents = _getModifierAndCompon.rangeComponents; + + switch (modifier) { + case '<': + return checkLessThan(versionComponents, rangeComponents); + case '<=': + return checkLessThanOrEqual(versionComponents, rangeComponents); + case '>=': + return checkGreaterThanOrEqual(versionComponents, rangeComponents); + case '>': + return checkGreaterThan(versionComponents, rangeComponents); + case '~': + case '~>': + return checkApproximateVersion(versionComponents, rangeComponents); + default: + return checkEqual(versionComponents, rangeComponents); + } +} + +/** + * Checks whether `a` is less than `b`. + * + * @param {array} a + * @param {array} b + * @returns {boolean} + */ +function checkLessThan(a, b) { + return compareComponents(a, b) === -1; +} + +/** + * Checks whether `a` is less than or equal to `b`. + * + * @param {array} a + * @param {array} b + * @returns {boolean} + */ +function checkLessThanOrEqual(a, b) { + var result = compareComponents(a, b); + return result === -1 || result === 0; +} + +/** + * Checks whether `a` is equal to `b`. + * + * @param {array} a + * @param {array} b + * @returns {boolean} + */ +function checkEqual(a, b) { + return compareComponents(a, b) === 0; +} + +/** + * Checks whether `a` is greater than or equal to `b`. + * + * @param {array} a + * @param {array} b + * @returns {boolean} + */ +function checkGreaterThanOrEqual(a, b) { + var result = compareComponents(a, b); + return result === 1 || result === 0; +} + +/** + * Checks whether `a` is greater than `b`. + * + * @param {array} a + * @param {array} b + * @returns {boolean} + */ +function checkGreaterThan(a, b) { + return compareComponents(a, b) === 1; +} + +/** + * Checks whether `a` is "reasonably close" to `b` (as described in + * https://www.npmjs.org/doc/misc/semver.html). For example, if `b` is "1.3.1" + * then "reasonably close" is defined as ">= 1.3.1 and < 1.4". + * + * @param {array} a + * @param {array} b + * @returns {boolean} + */ +function checkApproximateVersion(a, b) { + var lowerBound = b.slice(); + var upperBound = b.slice(); + + if (upperBound.length > 1) { + upperBound.pop(); + } + var lastIndex = upperBound.length - 1; + var numeric = parseInt(upperBound[lastIndex], 10); + if (isNumber(numeric)) { + upperBound[lastIndex] = numeric + 1 + ''; + } + + return checkGreaterThanOrEqual(a, lowerBound) && checkLessThan(a, upperBound); +} + +/** + * Extracts the optional modifier (<, <=, =, >=, >, ~, ~>) and version + * components from `range`. + * + * For example, given `range` ">= 1.2.3" returns an object with a `modifier` of + * `">="` and `components` of `[1, 2, 3]`. + * + * @param {string} range + * @returns {object} + */ +function getModifierAndComponents(range) { + var rangeComponents = range.split(componentRegex); + var matches = rangeComponents[0].match(modifierRegex); + !matches ? process.env.NODE_ENV !== 'production' ? invariant(false, 'expected regex to match but it did not') : invariant(false) : void 0; + + return { + modifier: matches[1], + rangeComponents: [matches[2]].concat(rangeComponents.slice(1)) + }; +} + +/** + * Determines if `number` is a number. + * + * @param {mixed} number + * @returns {boolean} + */ +function isNumber(number) { + return !isNaN(number) && isFinite(number); +} + +/** + * Tests whether `range` is a "simple" version number without any modifiers + * (">", "~" etc). + * + * @param {string} range + * @returns {boolean} + */ +function isSimpleVersion(range) { + return !getModifierAndComponents(range).modifier; +} + +/** + * Zero-pads array `array` until it is at least `length` long. + * + * @param {array} array + * @param {number} length + */ +function zeroPad(array, length) { + for (var i = array.length; i < length; i++) { + array[i] = '0'; + } +} + +/** + * Normalizes `a` and `b` in preparation for comparison by doing the following: + * + * - zero-pads `a` and `b` + * - marks any "x", "X" or "*" component in `b` as equivalent by zero-ing it out + * in both `a` and `b` + * - marks any final "*" component in `b` as a greedy wildcard by zero-ing it + * and all of its successors in `a` + * + * @param {array} a + * @param {array} b + * @returns {array>} + */ +function normalizeVersions(a, b) { + a = a.slice(); + b = b.slice(); + + zeroPad(a, b.length); + + // mark "x" and "*" components as equal + for (var i = 0; i < b.length; i++) { + var matches = b[i].match(/^[x*]$/i); + if (matches) { + b[i] = a[i] = '0'; + + // final "*" greedily zeros all remaining components + if (matches[0] === '*' && i === b.length - 1) { + for (var j = i; j < a.length; j++) { + a[j] = '0'; + } + } + } + } + + zeroPad(b, a.length); + + return [a, b]; +} + +/** + * Returns the numerical -- not the lexicographical -- ordering of `a` and `b`. + * + * For example, `10-alpha` is greater than `2-beta`. + * + * @param {string} a + * @param {string} b + * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to, + * or greater than `b`, respectively + */ +function compareNumeric(a, b) { + var aPrefix = a.match(numericRegex)[1]; + var bPrefix = b.match(numericRegex)[1]; + var aNumeric = parseInt(aPrefix, 10); + var bNumeric = parseInt(bPrefix, 10); + + if (isNumber(aNumeric) && isNumber(bNumeric) && aNumeric !== bNumeric) { + return compare(aNumeric, bNumeric); + } else { + return compare(a, b); + } +} + +/** + * Returns the ordering of `a` and `b`. + * + * @param {string|number} a + * @param {string|number} b + * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to, + * or greater than `b`, respectively + */ +function compare(a, b) { + !(typeof a === typeof b) ? process.env.NODE_ENV !== 'production' ? invariant(false, '"a" and "b" must be of the same type') : invariant(false) : void 0; + + if (a > b) { + return 1; + } else if (a < b) { + return -1; + } else { + return 0; + } +} + +/** + * Compares arrays of version components. + * + * @param {array} a + * @param {array} b + * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to, + * or greater than `b`, respectively + */ +function compareComponents(a, b) { + var _normalizeVersions = normalizeVersions(a, b), + aNormalized = _normalizeVersions[0], + bNormalized = _normalizeVersions[1]; + + for (var i = 0; i < bNormalized.length; i++) { + var result = compareNumeric(aNormalized[i], bNormalized[i]); + if (result) { + return result; + } + } + + return 0; +} + +var VersionRange = { + /** + * Checks whether `version` satisfies the `range` specification. + * + * We support a subset of the expressions defined in + * https://www.npmjs.org/doc/misc/semver.html: + * + * version Must match version exactly + * =version Same as just version + * >version Must be greater than version + * >=version Must be greater than or equal to version + * = 1.2.3 and < 1.3" + * ~>version Equivalent to ~version + * 1.2.x Must match "1.2.x", where "x" is a wildcard that matches + * anything + * 1.2.* Similar to "1.2.x", but "*" in the trailing position is a + * "greedy" wildcard, so will match any number of additional + * components: + * "1.2.*" will match "1.2.1", "1.2.1.1", "1.2.1.1.1" etc + * * Any version + * "" (Empty string) Same as * + * v1 - v2 Equivalent to ">= v1 and <= v2" + * r1 || r2 Passes if either r1 or r2 are satisfied + * + * @param {string} range + * @param {string} version + * @returns {boolean} + */ + contains: function contains(range, version) { + return checkOrExpression(range.trim(), version.trim()); + } +}; + +module.exports = VersionRange; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 169 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +var _hyphenPattern = /-(.)/g; + +/** + * Camelcases a hyphenated string, for example: + * + * > camelize('background-color') + * < "backgroundColor" + * + * @param {string} string + * @return {string} + */ +function camelize(string) { + return string.replace(_hyphenPattern, function (_, character) { + return character.toUpperCase(); + }); +} + +module.exports = camelize; + +/***/ }), +/* 170 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) { + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +var invariant = __webpack_require__(2); + +/** + * Convert array-like objects to arrays. + * + * This API assumes the caller knows the contents of the data type. For less + * well defined inputs use createArrayFromMixed. + * + * @param {object|function|filelist} obj + * @return {array} + */ +function toArray(obj) { + var length = obj.length; + + // Some browsers builtin objects can report typeof 'function' (e.g. NodeList + // in old versions of Safari). + !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0; + + !(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0; + + !(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0; + + !(typeof obj.callee !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0; + + // Old IE doesn't give collections access to hasOwnProperty. Assume inputs + // without method will throw during the slice call and skip straight to the + // fallback. + if (obj.hasOwnProperty) { + try { + return Array.prototype.slice.call(obj); + } catch (e) { + // IE < 9 does not support Array#slice on collections objects + } + } + + // Fall back to copying key by key. This assumes all keys have a value, + // so will not preserve sparsely populated inputs. + var ret = Array(length); + for (var ii = 0; ii < length; ii++) { + ret[ii] = obj[ii]; + } + return ret; +} + +/** + * Perform a heuristic test to determine if an object is "array-like". + * + * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" + * Joshu replied: "Mu." + * + * This function determines if its argument has "array nature": it returns + * true if the argument is an actual array, an `arguments' object, or an + * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). + * + * It will return false for other array-like objects like Filelist. + * + * @param {*} obj + * @return {boolean} + */ +function hasArrayNature(obj) { + return ( + // not null/false + !!obj && ( + // arrays are objects, NodeLists are functions in Safari + typeof obj == 'object' || typeof obj == 'function') && + // quacks like an array + 'length' in obj && + // not window + !('setInterval' in obj) && + // no DOM node should be considered an array-like + // a 'select' element has 'length' and 'item' properties on IE8 + typeof obj.nodeType != 'number' && ( + // a real array + Array.isArray(obj) || + // arguments + 'callee' in obj || + // HTMLCollection/NodeList + 'item' in obj) + ); +} + +/** + * Ensure that the argument is an array by wrapping it in an array if it is not. + * Creates a copy of the argument if it is already an array. + * + * This is mostly useful idiomatically: + * + * var createArrayFromMixed = require('createArrayFromMixed'); + * + * function takesOneOrMoreThings(things) { + * things = createArrayFromMixed(things); + * ... + * } + * + * This allows you to treat `things' as an array, but accept scalars in the API. + * + * If you need to convert an array-like object, like `arguments`, into an array + * use toArray instead. + * + * @param {*} obj + * @return {array} + */ +function createArrayFromMixed(obj) { + if (!hasArrayNature(obj)) { + return [obj]; + } else if (Array.isArray(obj)) { + return obj.slice(); + } else { + return toArray(obj); + } +} + +module.exports = createArrayFromMixed; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 171 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + + + +var isWebkit = typeof navigator !== 'undefined' && navigator.userAgent.indexOf('AppleWebKit') > -1; + +/** + * Gets the element with the document scroll properties such as `scrollLeft` and + * `scrollHeight`. This may differ across different browsers. + * + * NOTE: The return value can be null if the DOM is not yet ready. + * + * @param {?DOMDocument} doc Defaults to current document. + * @return {?DOMElement} + */ +function getDocumentScrollElement(doc) { + doc = doc || document; + if (doc.scrollingElement) { + return doc.scrollingElement; + } + return !isWebkit && doc.compatMode === 'CSS1Compat' ? doc.documentElement : doc.body; +} + +module.exports = getDocumentScrollElement; + +/***/ }), +/* 172 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +var getElementRect = __webpack_require__(173); + +/** + * Gets an element's position in pixels relative to the viewport. The returned + * object represents the position of the element's top left corner. + * + * @param {DOMElement} element + * @return {object} + */ +function getElementPosition(element) { + var rect = getElementRect(element); + return { + x: rect.left, + y: rect.top, + width: rect.right - rect.left, + height: rect.bottom - rect.top + }; +} + +module.exports = getElementPosition; + +/***/ }), +/* 173 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +var containsNode = __webpack_require__(39); + +/** + * Gets an element's bounding rect in pixels relative to the viewport. + * + * @param {DOMElement} elem + * @return {object} + */ +function getElementRect(elem) { + var docElem = elem.ownerDocument.documentElement; + + // FF 2, Safari 3 and Opera 9.5- do not support getBoundingClientRect(). + // IE9- will throw if the element is not in the document. + if (!('getBoundingClientRect' in elem) || !containsNode(docElem, elem)) { + return { + left: 0, + right: 0, + top: 0, + bottom: 0 + }; + } + + // Subtracts clientTop/Left because IE8- added a 2px border to the + // element (see http://fburl.com/1493213). IE 7 in + // Quicksmode does not report clientLeft/clientTop so there + // will be an unaccounted offset of 2px when in quirksmode + var rect = elem.getBoundingClientRect(); + + return { + left: Math.round(rect.left) - docElem.clientLeft, + right: Math.round(rect.right) - docElem.clientLeft, + top: Math.round(rect.top) - docElem.clientTop, + bottom: Math.round(rect.bottom) - docElem.clientTop + }; +} + +module.exports = getElementRect; + +/***/ }), +/* 174 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +var camelize = __webpack_require__(169); +var hyphenate = __webpack_require__(177); + +function asString(value) /*?string*/{ + return value == null ? value : String(value); +} + +function getStyleProperty( /*DOMNode*/node, /*string*/name) /*?string*/{ + var computedStyle = void 0; + + // W3C Standard + if (window.getComputedStyle) { + // In certain cases such as within an iframe in FF3, this returns null. + computedStyle = window.getComputedStyle(node, null); + if (computedStyle) { + return asString(computedStyle.getPropertyValue(hyphenate(name))); + } + } + // Safari + if (document.defaultView && document.defaultView.getComputedStyle) { + computedStyle = document.defaultView.getComputedStyle(node, null); + // A Safari bug causes this to return null for `display: none` elements. + if (computedStyle) { + return asString(computedStyle.getPropertyValue(hyphenate(name))); + } + if (name === 'display') { + return 'none'; + } + } + // Internet Explorer + if (node.currentStyle) { + if (name === 'float') { + return asString(node.currentStyle.cssFloat || node.currentStyle.styleFloat); + } + return asString(node.currentStyle[camelize(name)]); + } + return asString(node.style && node.style[camelize(name)]); +} + +module.exports = getStyleProperty; + +/***/ }), +/* 175 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + + + +/** + * Gets the scroll position of the supplied element or window. + * + * The return values are unbounded, unlike `getScrollPosition`. This means they + * may be negative or exceed the element boundaries (which is possible using + * inertial scrolling). + * + * @param {DOMWindow|DOMElement} scrollable + * @return {object} Map with `x` and `y` keys. + */ + +function getUnboundedScrollPosition(scrollable) { + if (scrollable.Window && scrollable instanceof scrollable.Window) { + return { + x: scrollable.pageXOffset || scrollable.document.documentElement.scrollLeft, + y: scrollable.pageYOffset || scrollable.document.documentElement.scrollTop + }; + } + return { + x: scrollable.scrollLeft, + y: scrollable.scrollTop + }; +} + +module.exports = getUnboundedScrollPosition; + +/***/ }), +/* 176 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +function getViewportWidth() { + var width = void 0; + if (document.documentElement) { + width = document.documentElement.clientWidth; + } + + if (!width && document.body) { + width = document.body.clientWidth; + } + + return width || 0; +} /** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + * @typechecks + */ + +function getViewportHeight() { + var height = void 0; + if (document.documentElement) { + height = document.documentElement.clientHeight; + } + + if (!height && document.body) { + height = document.body.clientHeight; + } + + return height || 0; +} + +/** + * Gets the viewport dimensions including any scrollbars. + */ +function getViewportDimensions() { + return { + width: window.innerWidth || getViewportWidth(), + height: window.innerHeight || getViewportHeight() + }; +} + +/** + * Gets the viewport dimensions excluding any scrollbars. + */ +getViewportDimensions.withoutScrollbars = function () { + return { + width: getViewportWidth(), + height: getViewportHeight() + }; +}; + +module.exports = getViewportDimensions; + +/***/ }), +/* 177 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +var _uppercasePattern = /([A-Z])/g; + +/** + * Hyphenates a camelcased string, for example: + * + * > hyphenate('backgroundColor') + * < "background-color" + * + * For CSS style names, use `hyphenateStyleName` instead which works properly + * with all vendor prefixes, including `ms`. + * + * @param {string} string + * @return {string} + */ +function hyphenate(string) { + return string.replace(_uppercasePattern, '-$1').toLowerCase(); +} + +module.exports = hyphenate; + +/***/ }), +/* 178 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +/** + * @param {*} object The object to check. + * @return {boolean} Whether or not the object is a DOM node. + */ +function isNode(object) { + var doc = object ? object.ownerDocument || object : document; + var defaultView = doc.defaultView || window; + return !!(object && (typeof defaultView.Node === 'function' ? object instanceof defaultView.Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); +} + +module.exports = isNode; + +/***/ }), +/* 179 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +var isNode = __webpack_require__(178); + +/** + * @param {*} object The object to check. + * @return {boolean} Whether or not the object is a DOM text node. + */ +function isTextNode(object) { + return isNode(object) && object.nodeType == 3; +} + +module.exports = isTextNode; + +/***/ }), +/* 180 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks static-only + */ + + + +/** + * Combines multiple className strings into one. + * http://jsperf.com/joinclasses-args-vs-array + * + * @param {...?string} className + * @return {string} + */ + +function joinClasses(className /*, ... */) { + if (!className) { + className = ''; + } + var nextClass = void 0; + var argLength = arguments.length; + if (argLength > 1) { + for (var ii = 1; ii < argLength; ii++) { + nextClass = arguments[ii]; + if (nextClass) { + className = (className ? className + ' ' : '') + nextClass; + } + } + } + return className; +} + +module.exports = joinClasses; + +/***/ }), +/* 181 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + + + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Executes the provided `callback` once for each enumerable own property in the + * object and constructs a new object from the results. The `callback` is + * invoked with three arguments: + * + * - the property value + * - the property name + * - the object being traversed + * + * Properties that are added after the call to `mapObject` will not be visited + * by `callback`. If the values of existing properties are changed, the value + * passed to `callback` will be the value at the time `mapObject` visits them. + * Properties that are deleted before being visited are not visited. + * + * @grep function objectMap() + * @grep function objMap() + * + * @param {?object} object + * @param {function} callback + * @param {*} context + * @return {?object} + */ +function mapObject(object, callback, context) { + if (!object) { + return null; + } + var result = {}; + for (var name in object) { + if (hasOwnProperty.call(object, name)) { + result[name] = callback.call(context, object[name], name, object); + } + } + return result; +} + +module.exports = mapObject; + +/***/ }), +/* 182 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + * @typechecks static-only + */ + + + +/** + * Memoizes the return value of a function that accepts one string argument. + */ + +function memoizeStringOnly(callback) { + var cache = {}; + return function (string) { + if (!cache.hasOwnProperty(string)) { + cache[string] = callback.call(this, string); + } + return cache[string]; + }; +} + +module.exports = memoizeStringOnly; + +/***/ }), +/* 183 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + + + +// setimmediate adds setImmediate to the global. We want to make sure we export +// the actual function. + +__webpack_require__(209); +module.exports = global.setImmediate; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) + +/***/ }), +/* 184 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +var ReactPropTypesSecret = __webpack_require__(43); + +function emptyFunction() {} + +module.exports = function() { + function shim(props, propName, componentName, location, propFullName, secret) { + if (secret === ReactPropTypesSecret) { + // It is still safe when called from React. + return; + } + var err = new Error( + 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + + 'Use PropTypes.checkPropTypes() to call them. ' + + 'Read more at http://fb.me/use-check-prop-types' + ); + err.name = 'Invariant Violation'; + throw err; + }; + shim.isRequired = shim; + function getShim() { + return shim; + }; + // Important! + // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. + var ReactPropTypes = { + array: shim, + bool: shim, + func: shim, + number: shim, + object: shim, + string: shim, + symbol: shim, + + any: shim, + arrayOf: getShim, + element: shim, + instanceOf: getShim, + node: shim, + objectOf: getShim, + oneOf: getShim, + oneOfType: getShim, + shape: getShim, + exact: getShim + }; + + ReactPropTypes.checkPropTypes = emptyFunction; + ReactPropTypes.PropTypes = ReactPropTypes; + + return ReactPropTypes; +}; + + +/***/ }), +/* 185 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +var assign = __webpack_require__(5); + +var ReactPropTypesSecret = __webpack_require__(43); +var checkPropTypes = __webpack_require__(42); + +var printWarning = function() {}; + +if (process.env.NODE_ENV !== 'production') { + printWarning = function(text) { + var message = 'Warning: ' + text; + if (typeof console !== 'undefined') { + console.error(message); + } + try { + // --- Welcome to debugging React --- + // This error was thrown as a convenience so that you can use this stack + // to find the callsite that caused this warning to fire. + throw new Error(message); + } catch (x) {} + }; +} + +function emptyFunctionThatReturnsNull() { + return null; +} + +module.exports = function(isValidElement, throwOnDirectAccess) { + /* global Symbol */ + var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. + + /** + * Returns the iterator method function contained on the iterable object. + * + * Be sure to invoke the function with the iterable as context: + * + * var iteratorFn = getIteratorFn(myIterable); + * if (iteratorFn) { + * var iterator = iteratorFn.call(myIterable); + * ... + * } + * + * @param {?object} maybeIterable + * @return {?function} + */ + function getIteratorFn(maybeIterable) { + var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); + if (typeof iteratorFn === 'function') { + return iteratorFn; + } + } + + /** + * Collection of methods that allow declaration and validation of props that are + * supplied to React components. Example usage: + * + * var Props = require('ReactPropTypes'); + * var MyArticle = React.createClass({ + * propTypes: { + * // An optional string prop named "description". + * description: Props.string, + * + * // A required enum prop named "category". + * category: Props.oneOf(['News','Photos']).isRequired, + * + * // A prop named "dialog" that requires an instance of Dialog. + * dialog: Props.instanceOf(Dialog).isRequired + * }, + * render: function() { ... } + * }); + * + * A more formal specification of how these methods are used: + * + * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) + * decl := ReactPropTypes.{type}(.isRequired)? + * + * Each and every declaration produces a function with the same signature. This + * allows the creation of custom validation functions. For example: + * + * var MyLink = React.createClass({ + * propTypes: { + * // An optional string or URI prop named "href". + * href: function(props, propName, componentName) { + * var propValue = props[propName]; + * if (propValue != null && typeof propValue !== 'string' && + * !(propValue instanceof URI)) { + * return new Error( + * 'Expected a string or an URI for ' + propName + ' in ' + + * componentName + * ); + * } + * } + * }, + * render: function() {...} + * }); + * + * @internal + */ + + var ANONYMOUS = '<>'; + + // Important! + // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. + var ReactPropTypes = { + array: createPrimitiveTypeChecker('array'), + bool: createPrimitiveTypeChecker('boolean'), + func: createPrimitiveTypeChecker('function'), + number: createPrimitiveTypeChecker('number'), + object: createPrimitiveTypeChecker('object'), + string: createPrimitiveTypeChecker('string'), + symbol: createPrimitiveTypeChecker('symbol'), + + any: createAnyTypeChecker(), + arrayOf: createArrayOfTypeChecker, + element: createElementTypeChecker(), + instanceOf: createInstanceTypeChecker, + node: createNodeChecker(), + objectOf: createObjectOfTypeChecker, + oneOf: createEnumTypeChecker, + oneOfType: createUnionTypeChecker, + shape: createShapeTypeChecker, + exact: createStrictShapeTypeChecker, + }; + + /** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ + /*eslint-disable no-self-compare*/ + function is(x, y) { + // SameValue algorithm + if (x === y) { + // Steps 1-5, 7-10 + // Steps 6.b-6.e: +0 != -0 + return x !== 0 || 1 / x === 1 / y; + } else { + // Step 6.a: NaN == NaN + return x !== x && y !== y; + } + } + /*eslint-enable no-self-compare*/ + + /** + * We use an Error-like object for backward compatibility as people may call + * PropTypes directly and inspect their output. However, we don't use real + * Errors anymore. We don't inspect their stack anyway, and creating them + * is prohibitively expensive if they are created too often, such as what + * happens in oneOfType() for any type before the one that matched. + */ + function PropTypeError(message) { + this.message = message; + this.stack = ''; + } + // Make `instanceof Error` still work for returned errors. + PropTypeError.prototype = Error.prototype; + + function createChainableTypeChecker(validate) { + if (process.env.NODE_ENV !== 'production') { + var manualPropTypeCallCache = {}; + var manualPropTypeWarningCount = 0; + } + function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { + componentName = componentName || ANONYMOUS; + propFullName = propFullName || propName; + + if (secret !== ReactPropTypesSecret) { + if (throwOnDirectAccess) { + // New behavior only for users of `prop-types` package + var err = new Error( + 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + + 'Use `PropTypes.checkPropTypes()` to call them. ' + + 'Read more at http://fb.me/use-check-prop-types' + ); + err.name = 'Invariant Violation'; + throw err; + } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') { + // Old behavior for people using React.PropTypes + var cacheKey = componentName + ':' + propName; + if ( + !manualPropTypeCallCache[cacheKey] && + // Avoid spamming the console because they are often not actionable except for lib authors + manualPropTypeWarningCount < 3 + ) { + printWarning( + 'You are manually calling a React.PropTypes validation ' + + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + + 'and will throw in the standalone `prop-types` package. ' + + 'You may be seeing this warning due to a third-party PropTypes ' + + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.' + ); + manualPropTypeCallCache[cacheKey] = true; + manualPropTypeWarningCount++; + } + } + } + if (props[propName] == null) { + if (isRequired) { + if (props[propName] === null) { + return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); + } + return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); + } + return null; + } else { + return validate(props, propName, componentName, location, propFullName); + } + } + + var chainedCheckType = checkType.bind(null, false); + chainedCheckType.isRequired = checkType.bind(null, true); + + return chainedCheckType; + } + + function createPrimitiveTypeChecker(expectedType) { + function validate(props, propName, componentName, location, propFullName, secret) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== expectedType) { + // `propValue` being instance of, say, date/regexp, pass the 'object' + // check, but we can offer a more precise error message here rather than + // 'of type `object`'. + var preciseType = getPreciseType(propValue); + + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createAnyTypeChecker() { + return createChainableTypeChecker(emptyFunctionThatReturnsNull); + } + + function createArrayOfTypeChecker(typeChecker) { + function validate(props, propName, componentName, location, propFullName) { + if (typeof typeChecker !== 'function') { + return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); + } + var propValue = props[propName]; + if (!Array.isArray(propValue)) { + var propType = getPropType(propValue); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); + } + for (var i = 0; i < propValue.length; i++) { + var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); + if (error instanceof Error) { + return error; + } + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createElementTypeChecker() { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + if (!isValidElement(propValue)) { + var propType = getPropType(propValue); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createInstanceTypeChecker(expectedClass) { + function validate(props, propName, componentName, location, propFullName) { + if (!(props[propName] instanceof expectedClass)) { + var expectedClassName = expectedClass.name || ANONYMOUS; + var actualClassName = getClassName(props[propName]); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createEnumTypeChecker(expectedValues) { + if (!Array.isArray(expectedValues)) { + process.env.NODE_ENV !== 'production' ? printWarning('Invalid argument supplied to oneOf, expected an instance of array.') : void 0; + return emptyFunctionThatReturnsNull; + } + + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + for (var i = 0; i < expectedValues.length; i++) { + if (is(propValue, expectedValues[i])) { + return null; + } + } + + var valuesString = JSON.stringify(expectedValues); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); + } + return createChainableTypeChecker(validate); + } + + function createObjectOfTypeChecker(typeChecker) { + function validate(props, propName, componentName, location, propFullName) { + if (typeof typeChecker !== 'function') { + return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); + } + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); + } + for (var key in propValue) { + if (propValue.hasOwnProperty(key)) { + var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); + if (error instanceof Error) { + return error; + } + } + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createUnionTypeChecker(arrayOfTypeCheckers) { + if (!Array.isArray(arrayOfTypeCheckers)) { + process.env.NODE_ENV !== 'production' ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; + return emptyFunctionThatReturnsNull; + } + + for (var i = 0; i < arrayOfTypeCheckers.length; i++) { + var checker = arrayOfTypeCheckers[i]; + if (typeof checker !== 'function') { + printWarning( + 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.' + ); + return emptyFunctionThatReturnsNull; + } + } + + function validate(props, propName, componentName, location, propFullName) { + for (var i = 0; i < arrayOfTypeCheckers.length; i++) { + var checker = arrayOfTypeCheckers[i]; + if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { + return null; + } + } + + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); + } + return createChainableTypeChecker(validate); + } + + function createNodeChecker() { + function validate(props, propName, componentName, location, propFullName) { + if (!isNode(props[propName])) { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createShapeTypeChecker(shapeTypes) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); + } + for (var key in shapeTypes) { + var checker = shapeTypes[key]; + if (!checker) { + continue; + } + var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); + if (error) { + return error; + } + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createStrictShapeTypeChecker(shapeTypes) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); + } + // We need to check all keys in case some are required but missing from + // props. + var allKeys = assign({}, props[propName], shapeTypes); + for (var key in allKeys) { + var checker = shapeTypes[key]; + if (!checker) { + return new PropTypeError( + 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') + ); + } + var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); + if (error) { + return error; + } + } + return null; + } + + return createChainableTypeChecker(validate); + } + + function isNode(propValue) { + switch (typeof propValue) { + case 'number': + case 'string': + case 'undefined': + return true; + case 'boolean': + return !propValue; + case 'object': + if (Array.isArray(propValue)) { + return propValue.every(isNode); + } + if (propValue === null || isValidElement(propValue)) { + return true; + } + + var iteratorFn = getIteratorFn(propValue); + if (iteratorFn) { + var iterator = iteratorFn.call(propValue); + var step; + if (iteratorFn !== propValue.entries) { + while (!(step = iterator.next()).done) { + if (!isNode(step.value)) { + return false; + } + } + } else { + // Iterator will provide entry [k,v] tuples rather than values. + while (!(step = iterator.next()).done) { + var entry = step.value; + if (entry) { + if (!isNode(entry[1])) { + return false; + } + } + } + } + } else { + return false; + } + + return true; + default: + return false; + } + } + + function isSymbol(propType, propValue) { + // Native Symbol. + if (propType === 'symbol') { + return true; + } + + // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' + if (propValue['@@toStringTag'] === 'Symbol') { + return true; + } + + // Fallback for non-spec compliant Symbols which are polyfilled. + if (typeof Symbol === 'function' && propValue instanceof Symbol) { + return true; + } + + return false; + } + + // Equivalent of `typeof` but with special handling for array and regexp. + function getPropType(propValue) { + var propType = typeof propValue; + if (Array.isArray(propValue)) { + return 'array'; + } + if (propValue instanceof RegExp) { + // Old webkits (at least until Android 4.0) return 'function' rather than + // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ + // passes PropTypes.object. + return 'object'; + } + if (isSymbol(propType, propValue)) { + return 'symbol'; + } + return propType; + } + + // This handles more types than `getPropType`. Only used for error messages. + // See `createPrimitiveTypeChecker`. + function getPreciseType(propValue) { + if (typeof propValue === 'undefined' || propValue === null) { + return '' + propValue; + } + var propType = getPropType(propValue); + if (propType === 'object') { + if (propValue instanceof Date) { + return 'date'; + } else if (propValue instanceof RegExp) { + return 'regexp'; + } + } + return propType; + } + + // Returns a string that is postfixed to a warning about an invalid type. + // For example, "undefined" or "of type array" + function getPostfixForTypeWarning(value) { + var type = getPreciseType(value); + switch (type) { + case 'array': + case 'object': + return 'an ' + type; + case 'boolean': + case 'date': + case 'regexp': + return 'a ' + type; + default: + return type; + } + } + + // Returns class name of the object, if any. + function getClassName(propValue) { + if (!propValue.constructor || !propValue.constructor.name) { + return ANONYMOUS; + } + return propValue.constructor.name; + } + + ReactPropTypes.checkPropTypes = checkPropTypes; + ReactPropTypes.PropTypes = ReactPropTypes; + + return ReactPropTypes; +}; + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 186 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _arrays = __webpack_require__(210); + +var _arrays2 = _interopRequireDefault(_arrays); + +var _reactAutowhatever = __webpack_require__(193); + +var _reactAutowhatever2 = _interopRequireDefault(_reactAutowhatever); + +var _theme = __webpack_require__(188); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var alwaysTrue = function alwaysTrue() { + return true; +}; +var defaultShouldRenderSuggestions = function defaultShouldRenderSuggestions(value) { + return value.trim().length > 0; +}; +var defaultRenderSuggestionsContainer = function defaultRenderSuggestionsContainer(_ref) { + var containerProps = _ref.containerProps, + children = _ref.children; + return _react2.default.createElement( + 'div', + containerProps, + children + ); +}; + +var Autosuggest = function (_Component) { + _inherits(Autosuggest, _Component); + + function Autosuggest(_ref2) { + var alwaysRenderSuggestions = _ref2.alwaysRenderSuggestions; + + _classCallCheck(this, Autosuggest); + + var _this = _possibleConstructorReturn(this, (Autosuggest.__proto__ || Object.getPrototypeOf(Autosuggest)).call(this)); + + _initialiseProps.call(_this); + + _this.state = { + isFocused: false, + isCollapsed: !alwaysRenderSuggestions, + highlightedSectionIndex: null, + highlightedSuggestionIndex: null, + highlightedSuggestion: null, + valueBeforeUpDown: null + }; + + _this.justPressedUpDown = false; + _this.justMouseEntered = false; + return _this; + } + + _createClass(Autosuggest, [{ + key: 'componentDidMount', + value: function componentDidMount() { + document.addEventListener('mousedown', this.onDocumentMouseDown); + + this.input = this.autowhatever.input; + this.suggestionsContainer = this.autowhatever.itemsContainer; + } + }, { + key: 'componentWillReceiveProps', + value: function componentWillReceiveProps(nextProps) { + if ((0, _arrays2.default)(nextProps.suggestions, this.props.suggestions)) { + if (nextProps.highlightFirstSuggestion && nextProps.suggestions.length > 0 && this.justPressedUpDown === false && this.justMouseEntered === false) { + this.highlightFirstSuggestion(); + } + } else { + if (this.willRenderSuggestions(nextProps)) { + if (this.state.isCollapsed && !this.justSelectedSuggestion) { + this.revealSuggestions(); + } + } else { + this.resetHighlightedSuggestion(); + } + } + } + }, { + key: 'componentDidUpdate', + value: function componentDidUpdate(prevProps, prevState) { + var _props = this.props, + suggestions = _props.suggestions, + onSuggestionHighlighted = _props.onSuggestionHighlighted, + highlightFirstSuggestion = _props.highlightFirstSuggestion; + + + if (!(0, _arrays2.default)(suggestions, prevProps.suggestions) && suggestions.length > 0 && highlightFirstSuggestion) { + this.highlightFirstSuggestion(); + return; + } + + if (onSuggestionHighlighted) { + var highlightedSuggestion = this.getHighlightedSuggestion(); + var prevHighlightedSuggestion = prevState.highlightedSuggestion; + + if (highlightedSuggestion != prevHighlightedSuggestion) { + onSuggestionHighlighted({ + suggestion: highlightedSuggestion + }); + } + } + } + }, { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + document.removeEventListener('mousedown', this.onDocumentMouseDown); + } + }, { + key: 'updateHighlightedSuggestion', + value: function updateHighlightedSuggestion(sectionIndex, suggestionIndex, prevValue) { + var _this2 = this; + + this.setState(function (state) { + var valueBeforeUpDown = state.valueBeforeUpDown; + + + if (suggestionIndex === null) { + valueBeforeUpDown = null; + } else if (valueBeforeUpDown === null && typeof prevValue !== 'undefined') { + valueBeforeUpDown = prevValue; + } + + return { + highlightedSectionIndex: sectionIndex, + highlightedSuggestionIndex: suggestionIndex, + highlightedSuggestion: suggestionIndex === null ? null : _this2.getSuggestion(sectionIndex, suggestionIndex), + valueBeforeUpDown: valueBeforeUpDown + }; + }); + } + }, { + key: 'resetHighlightedSuggestion', + value: function resetHighlightedSuggestion() { + var shouldResetValueBeforeUpDown = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + + this.setState(function (state) { + var valueBeforeUpDown = state.valueBeforeUpDown; + + + return { + highlightedSectionIndex: null, + highlightedSuggestionIndex: null, + highlightedSuggestion: null, + valueBeforeUpDown: shouldResetValueBeforeUpDown ? null : valueBeforeUpDown + }; + }); + } + }, { + key: 'revealSuggestions', + value: function revealSuggestions() { + this.setState({ + isCollapsed: false + }); + } + }, { + key: 'closeSuggestions', + value: function closeSuggestions() { + this.setState({ + highlightedSectionIndex: null, + highlightedSuggestionIndex: null, + highlightedSuggestion: null, + valueBeforeUpDown: null, + isCollapsed: true + }); + } + }, { + key: 'getSuggestion', + value: function getSuggestion(sectionIndex, suggestionIndex) { + var _props2 = this.props, + suggestions = _props2.suggestions, + multiSection = _props2.multiSection, + getSectionSuggestions = _props2.getSectionSuggestions; + + + if (multiSection) { + return getSectionSuggestions(suggestions[sectionIndex])[suggestionIndex]; + } + + return suggestions[suggestionIndex]; + } + }, { + key: 'getHighlightedSuggestion', + value: function getHighlightedSuggestion() { + var _state = this.state, + highlightedSectionIndex = _state.highlightedSectionIndex, + highlightedSuggestionIndex = _state.highlightedSuggestionIndex; + + + if (highlightedSuggestionIndex === null) { + return null; + } + + return this.getSuggestion(highlightedSectionIndex, highlightedSuggestionIndex); + } + }, { + key: 'getSuggestionValueByIndex', + value: function getSuggestionValueByIndex(sectionIndex, suggestionIndex) { + var getSuggestionValue = this.props.getSuggestionValue; + + + return getSuggestionValue(this.getSuggestion(sectionIndex, suggestionIndex)); + } + }, { + key: 'getSuggestionIndices', + value: function getSuggestionIndices(suggestionElement) { + var sectionIndex = suggestionElement.getAttribute('data-section-index'); + var suggestionIndex = suggestionElement.getAttribute('data-suggestion-index'); + + return { + sectionIndex: typeof sectionIndex === 'string' ? parseInt(sectionIndex, 10) : null, + suggestionIndex: parseInt(suggestionIndex, 10) + }; + } + }, { + key: 'findSuggestionElement', + value: function findSuggestionElement(startNode) { + var node = startNode; + + do { + if (node.getAttribute('data-suggestion-index') !== null) { + return node; + } + + node = node.parentNode; + } while (node !== null); + + console.error('Clicked element:', startNode); // eslint-disable-line no-console + throw new Error("Couldn't find suggestion element"); + } + }, { + key: 'maybeCallOnChange', + value: function maybeCallOnChange(event, newValue, method) { + var _props$inputProps = this.props.inputProps, + value = _props$inputProps.value, + onChange = _props$inputProps.onChange; + + + if (newValue !== value) { + onChange(event, { newValue: newValue, method: method }); + } + } + }, { + key: 'willRenderSuggestions', + value: function willRenderSuggestions(props) { + var suggestions = props.suggestions, + inputProps = props.inputProps, + shouldRenderSuggestions = props.shouldRenderSuggestions; + var value = inputProps.value; + + + return suggestions.length > 0 && shouldRenderSuggestions(value); + } + }, { + key: 'getQuery', + value: function getQuery() { + var inputProps = this.props.inputProps; + var value = inputProps.value; + var valueBeforeUpDown = this.state.valueBeforeUpDown; + + + return (valueBeforeUpDown === null ? value : valueBeforeUpDown).trim(); + } + }, { + key: 'render', + value: function render() { + var _this3 = this; + + var _props3 = this.props, + suggestions = _props3.suggestions, + renderInputComponent = _props3.renderInputComponent, + onSuggestionsFetchRequested = _props3.onSuggestionsFetchRequested, + renderSuggestion = _props3.renderSuggestion, + inputProps = _props3.inputProps, + multiSection = _props3.multiSection, + renderSectionTitle = _props3.renderSectionTitle, + id = _props3.id, + getSectionSuggestions = _props3.getSectionSuggestions, + theme = _props3.theme, + getSuggestionValue = _props3.getSuggestionValue, + alwaysRenderSuggestions = _props3.alwaysRenderSuggestions, + highlightFirstSuggestion = _props3.highlightFirstSuggestion; + var _state2 = this.state, + isFocused = _state2.isFocused, + isCollapsed = _state2.isCollapsed, + highlightedSectionIndex = _state2.highlightedSectionIndex, + highlightedSuggestionIndex = _state2.highlightedSuggestionIndex, + valueBeforeUpDown = _state2.valueBeforeUpDown; + + var shouldRenderSuggestions = alwaysRenderSuggestions ? alwaysTrue : this.props.shouldRenderSuggestions; + var value = inputProps.value, + _onFocus = inputProps.onFocus, + _onKeyDown = inputProps.onKeyDown; + + var willRenderSuggestions = this.willRenderSuggestions(this.props); + var isOpen = alwaysRenderSuggestions || isFocused && !isCollapsed && willRenderSuggestions; + var items = isOpen ? suggestions : []; + var autowhateverInputProps = _extends({}, inputProps, { + onFocus: function onFocus(event) { + if (!_this3.justSelectedSuggestion && !_this3.justClickedOnSuggestionsContainer) { + var shouldRender = shouldRenderSuggestions(value); + + _this3.setState({ + isFocused: true, + isCollapsed: !shouldRender + }); + + _onFocus && _onFocus(event); + + if (shouldRender) { + onSuggestionsFetchRequested({ value: value, reason: 'input-focused' }); + } + } + }, + onBlur: function onBlur(event) { + if (_this3.justClickedOnSuggestionsContainer) { + _this3.input.focus(); + return; + } + + _this3.blurEvent = event; + + if (!_this3.justSelectedSuggestion) { + _this3.onBlur(); + _this3.onSuggestionsClearRequested(); + } + }, + onChange: function onChange(event) { + var value = event.target.value; + + var shouldRender = shouldRenderSuggestions(value); + + _this3.maybeCallOnChange(event, value, 'type'); + + _this3.setState(_extends({}, highlightFirstSuggestion ? {} : { + highlightedSectionIndex: null, + highlightedSuggestionIndex: null, + highlightedSuggestion: null + }, { + valueBeforeUpDown: null, + isCollapsed: !shouldRender + })); + + if (shouldRender) { + onSuggestionsFetchRequested({ value: value, reason: 'input-changed' }); + } else { + _this3.onSuggestionsClearRequested(); + } + }, + onKeyDown: function onKeyDown(event, data) { + var keyCode = event.keyCode; + + + switch (keyCode) { + case 40: // ArrowDown + case 38: + // ArrowUp + if (isCollapsed) { + if (shouldRenderSuggestions(value)) { + onSuggestionsFetchRequested({ + value: value, + reason: 'suggestions-revealed' + }); + _this3.revealSuggestions(); + } + } else if (suggestions.length > 0) { + var newHighlightedSectionIndex = data.newHighlightedSectionIndex, + newHighlightedItemIndex = data.newHighlightedItemIndex; + + + var newValue = void 0; + + if (newHighlightedItemIndex === null) { + // valueBeforeUpDown can be null if, for example, user + // hovers on the first suggestion and then pressed Up. + // If that happens, use the original input value. + newValue = valueBeforeUpDown === null ? value : valueBeforeUpDown; + } else { + newValue = _this3.getSuggestionValueByIndex(newHighlightedSectionIndex, newHighlightedItemIndex); + } + + _this3.updateHighlightedSuggestion(newHighlightedSectionIndex, newHighlightedItemIndex, value); + _this3.maybeCallOnChange(event, newValue, keyCode === 40 ? 'down' : 'up'); + } + + event.preventDefault(); // Prevents the cursor from moving + + _this3.justPressedUpDown = true; + + setTimeout(function () { + _this3.justPressedUpDown = false; + }); + + break; + + // Enter + case 13: + { + // See #388 + if (event.keyCode === 229) { + break; + } + + var highlightedSuggestion = _this3.getHighlightedSuggestion(); + + if (isOpen && !alwaysRenderSuggestions) { + _this3.closeSuggestions(); + } + + if (highlightedSuggestion != null) { + var _newValue = getSuggestionValue(highlightedSuggestion); + + _this3.maybeCallOnChange(event, _newValue, 'enter'); + + _this3.onSuggestionSelected(event, { + suggestion: highlightedSuggestion, + suggestionValue: _newValue, + suggestionIndex: highlightedSuggestionIndex, + sectionIndex: highlightedSectionIndex, + method: 'enter' + }); + + _this3.justSelectedSuggestion = true; + + setTimeout(function () { + _this3.justSelectedSuggestion = false; + }); + } + + break; + } + + // Escape + case 27: + { + if (isOpen) { + // If input.type === 'search', the browser clears the input + // when Escape is pressed. We want to disable this default + // behaviour so that, when suggestions are shown, we just hide + // them, without clearing the input. + event.preventDefault(); + } + + var willCloseSuggestions = isOpen && !alwaysRenderSuggestions; + + if (valueBeforeUpDown === null) { + // Didn't interact with Up/Down + if (!willCloseSuggestions) { + var _newValue2 = ''; + + _this3.maybeCallOnChange(event, _newValue2, 'escape'); + + if (shouldRenderSuggestions(_newValue2)) { + onSuggestionsFetchRequested({ + value: _newValue2, + reason: 'escape-pressed' + }); + } else { + _this3.onSuggestionsClearRequested(); + } + } + } else { + // Interacted with Up/Down + _this3.maybeCallOnChange(event, valueBeforeUpDown, 'escape'); + } + + if (willCloseSuggestions) { + _this3.onSuggestionsClearRequested(); + _this3.closeSuggestions(); + } else { + _this3.resetHighlightedSuggestion(); + } + + break; + } + } + + _onKeyDown && _onKeyDown(event); + } + }); + var renderSuggestionData = { + query: this.getQuery() + }; + + return _react2.default.createElement(_reactAutowhatever2.default, { + multiSection: multiSection, + items: items, + renderInputComponent: renderInputComponent, + renderItemsContainer: this.renderSuggestionsContainer, + renderItem: renderSuggestion, + renderItemData: renderSuggestionData, + renderSectionTitle: renderSectionTitle, + getSectionItems: getSectionSuggestions, + highlightedSectionIndex: highlightedSectionIndex, + highlightedItemIndex: highlightedSuggestionIndex, + inputProps: autowhateverInputProps, + itemProps: this.itemProps, + theme: (0, _theme.mapToAutowhateverTheme)(theme), + id: id, + ref: this.storeAutowhateverRef + }); + } + }]); + + return Autosuggest; +}(_react.Component); + +Autosuggest.propTypes = { + suggestions: _propTypes2.default.array.isRequired, + onSuggestionsFetchRequested: function onSuggestionsFetchRequested(props, propName) { + var onSuggestionsFetchRequested = props[propName]; + + if (typeof onSuggestionsFetchRequested !== 'function') { + throw new Error("'onSuggestionsFetchRequested' must be implemented. See: https://github.com/moroshko/react-autosuggest#onSuggestionsFetchRequestedProp"); + } + }, + onSuggestionsClearRequested: function onSuggestionsClearRequested(props, propName) { + var onSuggestionsClearRequested = props[propName]; + + if (props.alwaysRenderSuggestions === false && typeof onSuggestionsClearRequested !== 'function') { + throw new Error("'onSuggestionsClearRequested' must be implemented. See: https://github.com/moroshko/react-autosuggest#onSuggestionsClearRequestedProp"); + } + }, + onSuggestionSelected: _propTypes2.default.func, + onSuggestionHighlighted: _propTypes2.default.func, + renderInputComponent: _propTypes2.default.func, + renderSuggestionsContainer: _propTypes2.default.func, + getSuggestionValue: _propTypes2.default.func.isRequired, + renderSuggestion: _propTypes2.default.func.isRequired, + inputProps: function inputProps(props, propName) { + var inputProps = props[propName]; + + if (!inputProps.hasOwnProperty('value')) { + throw new Error("'inputProps' must have 'value'."); + } + + if (!inputProps.hasOwnProperty('onChange')) { + throw new Error("'inputProps' must have 'onChange'."); + } + }, + shouldRenderSuggestions: _propTypes2.default.func, + alwaysRenderSuggestions: _propTypes2.default.bool, + multiSection: _propTypes2.default.bool, + renderSectionTitle: function renderSectionTitle(props, propName) { + var renderSectionTitle = props[propName]; + + if (props.multiSection === true && typeof renderSectionTitle !== 'function') { + throw new Error("'renderSectionTitle' must be implemented. See: https://github.com/moroshko/react-autosuggest#renderSectionTitleProp"); + } + }, + getSectionSuggestions: function getSectionSuggestions(props, propName) { + var getSectionSuggestions = props[propName]; + + if (props.multiSection === true && typeof getSectionSuggestions !== 'function') { + throw new Error("'getSectionSuggestions' must be implemented. See: https://github.com/moroshko/react-autosuggest#getSectionSuggestionsProp"); + } + }, + focusInputOnSuggestionClick: _propTypes2.default.bool, + highlightFirstSuggestion: _propTypes2.default.bool, + theme: _propTypes2.default.object, + id: _propTypes2.default.string +}; +Autosuggest.defaultProps = { + renderSuggestionsContainer: defaultRenderSuggestionsContainer, + shouldRenderSuggestions: defaultShouldRenderSuggestions, + alwaysRenderSuggestions: false, + multiSection: false, + focusInputOnSuggestionClick: true, + highlightFirstSuggestion: false, + theme: _theme.defaultTheme, + id: '1' +}; + +var _initialiseProps = function _initialiseProps() { + var _this4 = this; + + this.onDocumentMouseDown = function (event) { + _this4.justClickedOnSuggestionsContainer = false; + + var node = event.detail && event.detail.target || // This is for testing only. Please show me a better way to emulate this. + event.target; + + while (node !== null && node !== document) { + if (node.getAttribute('data-suggestion-index') !== null) { + // Suggestion was clicked + return; + } + + if (node === _this4.suggestionsContainer) { + // Something else inside suggestions container was clicked + _this4.justClickedOnSuggestionsContainer = true; + return; + } + + node = node.parentNode; + } + }; + + this.storeAutowhateverRef = function (autowhatever) { + if (autowhatever !== null) { + _this4.autowhatever = autowhatever; + } + }; + + this.onSuggestionMouseEnter = function (event, _ref3) { + var sectionIndex = _ref3.sectionIndex, + itemIndex = _ref3.itemIndex; + + _this4.updateHighlightedSuggestion(sectionIndex, itemIndex); + + _this4.justMouseEntered = true; + + setTimeout(function () { + _this4.justMouseEntered = false; + }); + }; + + this.highlightFirstSuggestion = function () { + _this4.updateHighlightedSuggestion(_this4.props.multiSection ? 0 : null, 0); + }; + + this.onSuggestionMouseDown = function () { + _this4.justSelectedSuggestion = true; + }; + + this.onSuggestionsClearRequested = function () { + var onSuggestionsClearRequested = _this4.props.onSuggestionsClearRequested; + + + onSuggestionsClearRequested && onSuggestionsClearRequested(); + }; + + this.onSuggestionSelected = function (event, data) { + var _props4 = _this4.props, + alwaysRenderSuggestions = _props4.alwaysRenderSuggestions, + onSuggestionSelected = _props4.onSuggestionSelected, + onSuggestionsFetchRequested = _props4.onSuggestionsFetchRequested; + + + onSuggestionSelected && onSuggestionSelected(event, data); + + if (alwaysRenderSuggestions) { + onSuggestionsFetchRequested({ + value: data.suggestionValue, + reason: 'suggestion-selected' + }); + } else { + _this4.onSuggestionsClearRequested(); + } + + _this4.resetHighlightedSuggestion(); + }; + + this.onSuggestionClick = function (event) { + var _props5 = _this4.props, + alwaysRenderSuggestions = _props5.alwaysRenderSuggestions, + focusInputOnSuggestionClick = _props5.focusInputOnSuggestionClick; + + var _getSuggestionIndices = _this4.getSuggestionIndices(_this4.findSuggestionElement(event.target)), + sectionIndex = _getSuggestionIndices.sectionIndex, + suggestionIndex = _getSuggestionIndices.suggestionIndex; + + var clickedSuggestion = _this4.getSuggestion(sectionIndex, suggestionIndex); + var clickedSuggestionValue = _this4.props.getSuggestionValue(clickedSuggestion); + + _this4.maybeCallOnChange(event, clickedSuggestionValue, 'click'); + _this4.onSuggestionSelected(event, { + suggestion: clickedSuggestion, + suggestionValue: clickedSuggestionValue, + suggestionIndex: suggestionIndex, + sectionIndex: sectionIndex, + method: 'click' + }); + + if (!alwaysRenderSuggestions) { + _this4.closeSuggestions(); + } + + if (focusInputOnSuggestionClick === true) { + _this4.input.focus(); + } else { + _this4.onBlur(); + } + + setTimeout(function () { + _this4.justSelectedSuggestion = false; + }); + }; + + this.onBlur = function () { + var _props6 = _this4.props, + inputProps = _props6.inputProps, + shouldRenderSuggestions = _props6.shouldRenderSuggestions; + var value = inputProps.value, + onBlur = inputProps.onBlur; + + var highlightedSuggestion = _this4.getHighlightedSuggestion(); + var shouldRender = shouldRenderSuggestions(value); + + _this4.setState({ + isFocused: false, + highlightedSectionIndex: null, + highlightedSuggestionIndex: null, + highlightedSuggestion: null, + valueBeforeUpDown: null, + isCollapsed: !shouldRender + }); + + onBlur && onBlur(_this4.blurEvent, { highlightedSuggestion: highlightedSuggestion }); + }; + + this.resetHighlightedSuggestionOnMouseLeave = function () { + _this4.resetHighlightedSuggestion(false); // shouldResetValueBeforeUpDown + }; + + this.itemProps = function (_ref4) { + var sectionIndex = _ref4.sectionIndex, + itemIndex = _ref4.itemIndex; + + return { + 'data-section-index': sectionIndex, + 'data-suggestion-index': itemIndex, + onMouseEnter: _this4.onSuggestionMouseEnter, + onMouseLeave: _this4.resetHighlightedSuggestionOnMouseLeave, + onMouseDown: _this4.onSuggestionMouseDown, + onTouchStart: _this4.onSuggestionMouseDown, // Because on iOS `onMouseDown` is not triggered + onClick: _this4.onSuggestionClick + }; + }; + + this.renderSuggestionsContainer = function (_ref5) { + var containerProps = _ref5.containerProps, + children = _ref5.children; + var renderSuggestionsContainer = _this4.props.renderSuggestionsContainer; + + + return renderSuggestionsContainer({ + containerProps: containerProps, + children: children, + query: _this4.getQuery() + }); + }; +}; + +exports.default = Autosuggest; + +/***/ }), +/* 187 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(186).default; + +/***/ }), +/* 188 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var defaultTheme = exports.defaultTheme = { + container: 'react-autosuggest__container', + containerOpen: 'react-autosuggest__container--open', + input: 'react-autosuggest__input', + inputOpen: 'react-autosuggest__input--open', + inputFocused: 'react-autosuggest__input--focused', + suggestionsContainer: 'react-autosuggest__suggestions-container', + suggestionsContainerOpen: 'react-autosuggest__suggestions-container--open', + suggestionsList: 'react-autosuggest__suggestions-list', + suggestion: 'react-autosuggest__suggestion', + suggestionFirst: 'react-autosuggest__suggestion--first', + suggestionHighlighted: 'react-autosuggest__suggestion--highlighted', + sectionContainer: 'react-autosuggest__section-container', + sectionContainerFirst: 'react-autosuggest__section-container--first', + sectionTitle: 'react-autosuggest__section-title' +}; + +var mapToAutowhateverTheme = exports.mapToAutowhateverTheme = function mapToAutowhateverTheme(theme) { + var result = {}; + + for (var key in theme) { + switch (key) { + case 'suggestionsContainer': + result['itemsContainer'] = theme[key]; + break; + + case 'suggestionsContainerOpen': + result['itemsContainerOpen'] = theme[key]; + break; + + case 'suggestion': + result['item'] = theme[key]; + break; + + case 'suggestionFirst': + result['itemFirst'] = theme[key]; + break; + + case 'suggestionHighlighted': + result['itemHighlighted'] = theme[key]; + break; + + case 'suggestionsList': + result['itemsList'] = theme[key]; + break; + + default: + result[key] = theme[key]; + } + } + + return result; +}; + +/***/ }), +/* 189 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _sectionIterator = __webpack_require__(208); + +var _sectionIterator2 = _interopRequireDefault(_sectionIterator); + +var _reactThemeable = __webpack_require__(203); + +var _reactThemeable2 = _interopRequireDefault(_reactThemeable); + +var _SectionTitle = __webpack_require__(192); + +var _SectionTitle2 = _interopRequireDefault(_SectionTitle); + +var _ItemsList = __webpack_require__(191); + +var _ItemsList2 = _interopRequireDefault(_ItemsList); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var emptyObject = {}; +var defaultRenderInputComponent = function defaultRenderInputComponent(props) { + return _react2.default.createElement('input', props); +}; +var defaultRenderItemsContainer = function defaultRenderItemsContainer(_ref) { + var containerProps = _ref.containerProps, + children = _ref.children; + return _react2.default.createElement( + 'div', + containerProps, + children + ); +}; +var defaultTheme = { + container: 'react-autowhatever__container', + containerOpen: 'react-autowhatever__container--open', + input: 'react-autowhatever__input', + inputOpen: 'react-autowhatever__input--open', + inputFocused: 'react-autowhatever__input--focused', + itemsContainer: 'react-autowhatever__items-container', + itemsContainerOpen: 'react-autowhatever__items-container--open', + itemsList: 'react-autowhatever__items-list', + item: 'react-autowhatever__item', + itemFirst: 'react-autowhatever__item--first', + itemHighlighted: 'react-autowhatever__item--highlighted', + sectionContainer: 'react-autowhatever__section-container', + sectionContainerFirst: 'react-autowhatever__section-container--first', + sectionTitle: 'react-autowhatever__section-title' +}; + +var Autowhatever = function (_Component) { + _inherits(Autowhatever, _Component); + + function Autowhatever(props) { + _classCallCheck(this, Autowhatever); + + var _this = _possibleConstructorReturn(this, (Autowhatever.__proto__ || Object.getPrototypeOf(Autowhatever)).call(this, props)); + + _this.storeInputReference = function (input) { + if (input !== null) { + _this.input = input; + } + }; + + _this.storeItemsContainerReference = function (itemsContainer) { + if (itemsContainer !== null) { + _this.itemsContainer = itemsContainer; + } + }; + + _this.onHighlightedItemChange = function (highlightedItem) { + _this.highlightedItem = highlightedItem; + }; + + _this.getItemId = function (sectionIndex, itemIndex) { + if (itemIndex === null) { + return null; + } + + var id = _this.props.id; + + var section = sectionIndex === null ? '' : 'section-' + sectionIndex; + + return 'react-autowhatever-' + id + '-' + section + '-item-' + itemIndex; + }; + + _this.onFocus = function (event) { + var inputProps = _this.props.inputProps; + + + _this.setState({ + isInputFocused: true + }); + + inputProps.onFocus && inputProps.onFocus(event); + }; + + _this.onBlur = function (event) { + var inputProps = _this.props.inputProps; + + + _this.setState({ + isInputFocused: false + }); + + inputProps.onBlur && inputProps.onBlur(event); + }; + + _this.onKeyDown = function (event) { + var _this$props = _this.props, + inputProps = _this$props.inputProps, + highlightedSectionIndex = _this$props.highlightedSectionIndex, + highlightedItemIndex = _this$props.highlightedItemIndex; + + + switch (event.key) { + case 'ArrowDown': + case 'ArrowUp': + { + var nextPrev = event.key === 'ArrowDown' ? 'next' : 'prev'; + + var _this$sectionIterator = _this.sectionIterator[nextPrev]([highlightedSectionIndex, highlightedItemIndex]), + _this$sectionIterator2 = _slicedToArray(_this$sectionIterator, 2), + newHighlightedSectionIndex = _this$sectionIterator2[0], + newHighlightedItemIndex = _this$sectionIterator2[1]; + + inputProps.onKeyDown(event, { newHighlightedSectionIndex: newHighlightedSectionIndex, newHighlightedItemIndex: newHighlightedItemIndex }); + break; + } + + default: + inputProps.onKeyDown(event, { highlightedSectionIndex: highlightedSectionIndex, highlightedItemIndex: highlightedItemIndex }); + } + }; + + _this.highlightedItem = null; + + _this.state = { + isInputFocused: false + }; + + _this.setSectionsItems(props); + _this.setSectionIterator(props); + _this.setTheme(props); + return _this; + } + + _createClass(Autowhatever, [{ + key: 'componentDidMount', + value: function componentDidMount() { + this.ensureHighlightedItemIsVisible(); + } + }, { + key: 'componentWillReceiveProps', + value: function componentWillReceiveProps(nextProps) { + if (nextProps.items !== this.props.items) { + this.setSectionsItems(nextProps); + } + + if (nextProps.items !== this.props.items || nextProps.multiSection !== this.props.multiSection) { + this.setSectionIterator(nextProps); + } + + if (nextProps.theme !== this.props.theme) { + this.setTheme(nextProps); + } + } + }, { + key: 'componentDidUpdate', + value: function componentDidUpdate() { + this.ensureHighlightedItemIsVisible(); + } + }, { + key: 'setSectionsItems', + value: function setSectionsItems(props) { + if (props.multiSection) { + this.sectionsItems = props.items.map(function (section) { + return props.getSectionItems(section); + }); + this.sectionsLengths = this.sectionsItems.map(function (items) { + return items.length; + }); + this.allSectionsAreEmpty = this.sectionsLengths.every(function (itemsCount) { + return itemsCount === 0; + }); + } + } + }, { + key: 'setSectionIterator', + value: function setSectionIterator(props) { + this.sectionIterator = (0, _sectionIterator2.default)({ + multiSection: props.multiSection, + data: props.multiSection ? this.sectionsLengths : props.items.length + }); + } + }, { + key: 'setTheme', + value: function setTheme(props) { + this.theme = (0, _reactThemeable2.default)(props.theme); + } + }, { + key: 'renderSections', + value: function renderSections() { + var _this2 = this; + + if (this.allSectionsAreEmpty) { + return null; + } + + var theme = this.theme; + var _props = this.props, + id = _props.id, + items = _props.items, + renderItem = _props.renderItem, + renderItemData = _props.renderItemData, + renderSectionTitle = _props.renderSectionTitle, + highlightedSectionIndex = _props.highlightedSectionIndex, + highlightedItemIndex = _props.highlightedItemIndex, + itemProps = _props.itemProps; + + + return items.map(function (section, sectionIndex) { + var keyPrefix = 'react-autowhatever-' + id + '-'; + var sectionKeyPrefix = keyPrefix + 'section-' + sectionIndex + '-'; + var isFirstSection = sectionIndex === 0; + + // `key` is provided by theme() + /* eslint-disable react/jsx-key */ + return _react2.default.createElement( + 'div', + theme(sectionKeyPrefix + 'container', 'sectionContainer', isFirstSection && 'sectionContainerFirst'), + _react2.default.createElement(_SectionTitle2.default, { + section: section, + renderSectionTitle: renderSectionTitle, + theme: theme, + sectionKeyPrefix: sectionKeyPrefix + }), + _react2.default.createElement(_ItemsList2.default, { + items: _this2.sectionsItems[sectionIndex], + itemProps: itemProps, + renderItem: renderItem, + renderItemData: renderItemData, + sectionIndex: sectionIndex, + highlightedItemIndex: highlightedSectionIndex === sectionIndex ? highlightedItemIndex : null, + onHighlightedItemChange: _this2.onHighlightedItemChange, + getItemId: _this2.getItemId, + theme: theme, + keyPrefix: keyPrefix, + ref: _this2.storeItemsListReference + }) + ); + /* eslint-enable react/jsx-key */ + }); + } + }, { + key: 'renderItems', + value: function renderItems() { + var items = this.props.items; + + + if (items.length === 0) { + return null; + } + + var theme = this.theme; + var _props2 = this.props, + id = _props2.id, + renderItem = _props2.renderItem, + renderItemData = _props2.renderItemData, + highlightedSectionIndex = _props2.highlightedSectionIndex, + highlightedItemIndex = _props2.highlightedItemIndex, + itemProps = _props2.itemProps; + + + return _react2.default.createElement(_ItemsList2.default, { + items: items, + itemProps: itemProps, + renderItem: renderItem, + renderItemData: renderItemData, + highlightedItemIndex: highlightedSectionIndex === null ? highlightedItemIndex : null, + onHighlightedItemChange: this.onHighlightedItemChange, + getItemId: this.getItemId, + theme: theme, + keyPrefix: 'react-autowhatever-' + id + '-' + }); + } + }, { + key: 'ensureHighlightedItemIsVisible', + value: function ensureHighlightedItemIsVisible() { + var highlightedItem = this.highlightedItem; + + + if (!highlightedItem) { + return; + } + + var itemsContainer = this.itemsContainer; + + var itemOffsetRelativeToContainer = highlightedItem.offsetParent === itemsContainer ? highlightedItem.offsetTop : highlightedItem.offsetTop - itemsContainer.offsetTop; + + var scrollTop = itemsContainer.scrollTop; // Top of the visible area + + if (itemOffsetRelativeToContainer < scrollTop) { + // Item is off the top of the visible area + scrollTop = itemOffsetRelativeToContainer; + } else if (itemOffsetRelativeToContainer + highlightedItem.offsetHeight > scrollTop + itemsContainer.offsetHeight) { + // Item is off the bottom of the visible area + scrollTop = itemOffsetRelativeToContainer + highlightedItem.offsetHeight - itemsContainer.offsetHeight; + } + + if (scrollTop !== itemsContainer.scrollTop) { + itemsContainer.scrollTop = scrollTop; + } + } + }, { + key: 'render', + value: function render() { + var theme = this.theme; + var _props3 = this.props, + id = _props3.id, + multiSection = _props3.multiSection, + renderInputComponent = _props3.renderInputComponent, + renderItemsContainer = _props3.renderItemsContainer, + highlightedSectionIndex = _props3.highlightedSectionIndex, + highlightedItemIndex = _props3.highlightedItemIndex; + var isInputFocused = this.state.isInputFocused; + + var renderedItems = multiSection ? this.renderSections() : this.renderItems(); + var isOpen = renderedItems !== null; + var ariaActivedescendant = this.getItemId(highlightedSectionIndex, highlightedItemIndex); + var itemsContainerId = 'react-autowhatever-' + id; + var containerProps = _extends({ + role: 'combobox', + 'aria-haspopup': 'listbox', + 'aria-owns': itemsContainerId, + 'aria-expanded': isOpen + }, theme('react-autowhatever-' + id + '-container', 'container', isOpen && 'containerOpen')); + var inputComponent = renderInputComponent(_extends({ + type: 'text', + value: '', + autoComplete: 'off', + 'aria-autocomplete': 'list', + 'aria-controls': itemsContainerId, + 'aria-activedescendant': ariaActivedescendant + }, theme('react-autowhatever-' + id + '-input', 'input', isOpen && 'inputOpen', isInputFocused && 'inputFocused'), this.props.inputProps, { + onFocus: this.onFocus, + onBlur: this.onBlur, + onKeyDown: this.props.inputProps.onKeyDown && this.onKeyDown, + ref: this.storeInputReference + })); + var itemsContainer = renderItemsContainer({ + containerProps: _extends({ + id: itemsContainerId, + role: 'listbox' + }, theme('react-autowhatever-' + id + '-items-container', 'itemsContainer', isOpen && 'itemsContainerOpen'), { + ref: this.storeItemsContainerReference + }), + children: renderedItems + }); + + return _react2.default.createElement( + 'div', + containerProps, + inputComponent, + itemsContainer + ); + } + }]); + + return Autowhatever; +}(_react.Component); + +Autowhatever.propTypes = { + id: _propTypes2.default.string, // Used in aria-* attributes. If multiple Autowhatever's are rendered on a page, they must have unique ids. + multiSection: _propTypes2.default.bool, // Indicates whether a multi section layout should be rendered. + renderInputComponent: _propTypes2.default.func, // When specified, it is used to render the input element. + renderItemsContainer: _propTypes2.default.func, // Renders the items container. + items: _propTypes2.default.array.isRequired, // Array of items or sections to render. + renderItem: _propTypes2.default.func, // This function renders a single item. + renderItemData: _propTypes2.default.object, // Arbitrary data that will be passed to renderItem() + renderSectionTitle: _propTypes2.default.func, // This function gets a section and renders its title. + getSectionItems: _propTypes2.default.func, // This function gets a section and returns its items, which will be passed into `renderItem` for rendering. + inputProps: _propTypes2.default.object, // Arbitrary input props + itemProps: _propTypes2.default.oneOfType([// Arbitrary item props + _propTypes2.default.object, _propTypes2.default.func]), + highlightedSectionIndex: _propTypes2.default.number, // Section index of the highlighted item + highlightedItemIndex: _propTypes2.default.number, // Highlighted item index (within a section) + theme: _propTypes2.default.oneOfType([// Styles. See: https://github.com/markdalgleish/react-themeable + _propTypes2.default.object, _propTypes2.default.array]) +}; +Autowhatever.defaultProps = { + id: '1', + multiSection: false, + renderInputComponent: defaultRenderInputComponent, + renderItemsContainer: defaultRenderItemsContainer, + renderItem: function renderItem() { + throw new Error('`renderItem` must be provided'); + }, + renderItemData: emptyObject, + renderSectionTitle: function renderSectionTitle() { + throw new Error('`renderSectionTitle` must be provided'); + }, + getSectionItems: function getSectionItems() { + throw new Error('`getSectionItems` must be provided'); + }, + inputProps: emptyObject, + itemProps: emptyObject, + highlightedSectionIndex: null, + highlightedItemIndex: null, + theme: defaultTheme +}; +exports.default = Autowhatever; + +/***/ }), +/* 190 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _compareObjects = __webpack_require__(44); + +var _compareObjects2 = _interopRequireDefault(_compareObjects); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var Item = function (_Component) { + _inherits(Item, _Component); + + function Item() { + var _ref; + + var _temp, _this, _ret; + + _classCallCheck(this, Item); + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Item.__proto__ || Object.getPrototypeOf(Item)).call.apply(_ref, [this].concat(args))), _this), _this.storeItemReference = function (item) { + if (item !== null) { + _this.item = item; + } + }, _this.onMouseEnter = function (event) { + var _this$props = _this.props, + sectionIndex = _this$props.sectionIndex, + itemIndex = _this$props.itemIndex; + + + _this.props.onMouseEnter(event, { sectionIndex: sectionIndex, itemIndex: itemIndex }); + }, _this.onMouseLeave = function (event) { + var _this$props2 = _this.props, + sectionIndex = _this$props2.sectionIndex, + itemIndex = _this$props2.itemIndex; + + + _this.props.onMouseLeave(event, { sectionIndex: sectionIndex, itemIndex: itemIndex }); + }, _this.onMouseDown = function (event) { + var _this$props3 = _this.props, + sectionIndex = _this$props3.sectionIndex, + itemIndex = _this$props3.itemIndex; + + + _this.props.onMouseDown(event, { sectionIndex: sectionIndex, itemIndex: itemIndex }); + }, _this.onClick = function (event) { + var _this$props4 = _this.props, + sectionIndex = _this$props4.sectionIndex, + itemIndex = _this$props4.itemIndex; + + + _this.props.onClick(event, { sectionIndex: sectionIndex, itemIndex: itemIndex }); + }, _temp), _possibleConstructorReturn(_this, _ret); + } + + _createClass(Item, [{ + key: 'shouldComponentUpdate', + value: function shouldComponentUpdate(nextProps) { + return (0, _compareObjects2.default)(nextProps, this.props, ['renderItemData']); + } + }, { + key: 'render', + value: function render() { + var _props = this.props, + isHighlighted = _props.isHighlighted, + item = _props.item, + renderItem = _props.renderItem, + renderItemData = _props.renderItemData, + restProps = _objectWithoutProperties(_props, ['isHighlighted', 'item', 'renderItem', 'renderItemData']); + + delete restProps.sectionIndex; + delete restProps.itemIndex; + + if (typeof restProps.onMouseEnter === 'function') { + restProps.onMouseEnter = this.onMouseEnter; + } + + if (typeof restProps.onMouseLeave === 'function') { + restProps.onMouseLeave = this.onMouseLeave; + } + + if (typeof restProps.onMouseDown === 'function') { + restProps.onMouseDown = this.onMouseDown; + } + + if (typeof restProps.onClick === 'function') { + restProps.onClick = this.onClick; + } + + return _react2.default.createElement( + 'li', + _extends({ role: 'option' }, restProps, { ref: this.storeItemReference }), + renderItem(item, _extends({ isHighlighted: isHighlighted }, renderItemData)) + ); + } + }]); + + return Item; +}(_react.Component); + +Item.propTypes = { + sectionIndex: _propTypes2.default.number, + isHighlighted: _propTypes2.default.bool.isRequired, + itemIndex: _propTypes2.default.number.isRequired, + item: _propTypes2.default.any.isRequired, + renderItem: _propTypes2.default.func.isRequired, + renderItemData: _propTypes2.default.object.isRequired, + onMouseEnter: _propTypes2.default.func, + onMouseLeave: _propTypes2.default.func, + onMouseDown: _propTypes2.default.func, + onClick: _propTypes2.default.func +}; +exports.default = Item; + +/***/ }), +/* 191 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _Item = __webpack_require__(190); + +var _Item2 = _interopRequireDefault(_Item); + +var _compareObjects = __webpack_require__(44); + +var _compareObjects2 = _interopRequireDefault(_compareObjects); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var ItemsList = function (_Component) { + _inherits(ItemsList, _Component); + + function ItemsList() { + var _ref; + + var _temp, _this, _ret; + + _classCallCheck(this, ItemsList); + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = ItemsList.__proto__ || Object.getPrototypeOf(ItemsList)).call.apply(_ref, [this].concat(args))), _this), _this.storeHighlightedItemReference = function (highlightedItem) { + _this.props.onHighlightedItemChange(highlightedItem === null ? null : highlightedItem.item); + }, _temp), _possibleConstructorReturn(_this, _ret); + } + + _createClass(ItemsList, [{ + key: 'shouldComponentUpdate', + value: function shouldComponentUpdate(nextProps) { + return (0, _compareObjects2.default)(nextProps, this.props, ['itemProps']); + } + }, { + key: 'render', + value: function render() { + var _this2 = this; + + var _props = this.props, + items = _props.items, + itemProps = _props.itemProps, + renderItem = _props.renderItem, + renderItemData = _props.renderItemData, + sectionIndex = _props.sectionIndex, + highlightedItemIndex = _props.highlightedItemIndex, + getItemId = _props.getItemId, + theme = _props.theme, + keyPrefix = _props.keyPrefix; + + var sectionPrefix = sectionIndex === null ? keyPrefix : keyPrefix + 'section-' + sectionIndex + '-'; + var isItemPropsFunction = typeof itemProps === 'function'; + + return _react2.default.createElement( + 'ul', + _extends({ role: 'listbox' }, theme(sectionPrefix + 'items-list', 'itemsList')), + items.map(function (item, itemIndex) { + var isFirst = itemIndex === 0; + var isHighlighted = itemIndex === highlightedItemIndex; + var itemKey = sectionPrefix + 'item-' + itemIndex; + var itemPropsObj = isItemPropsFunction ? itemProps({ sectionIndex: sectionIndex, itemIndex: itemIndex }) : itemProps; + var allItemProps = _extends({ + id: getItemId(sectionIndex, itemIndex), + 'aria-selected': isHighlighted + }, theme(itemKey, 'item', isFirst && 'itemFirst', isHighlighted && 'itemHighlighted'), itemPropsObj); + + if (isHighlighted) { + allItemProps.ref = _this2.storeHighlightedItemReference; + } + + // `key` is provided by theme() + /* eslint-disable react/jsx-key */ + return _react2.default.createElement(_Item2.default, _extends({}, allItemProps, { + sectionIndex: sectionIndex, + isHighlighted: isHighlighted, + itemIndex: itemIndex, + item: item, + renderItem: renderItem, + renderItemData: renderItemData + })); + /* eslint-enable react/jsx-key */ + }) + ); + } + }]); + + return ItemsList; +}(_react.Component); + +ItemsList.propTypes = { + items: _propTypes2.default.array.isRequired, + itemProps: _propTypes2.default.oneOfType([_propTypes2.default.object, _propTypes2.default.func]), + renderItem: _propTypes2.default.func.isRequired, + renderItemData: _propTypes2.default.object.isRequired, + sectionIndex: _propTypes2.default.number, + highlightedItemIndex: _propTypes2.default.number, + onHighlightedItemChange: _propTypes2.default.func.isRequired, + getItemId: _propTypes2.default.func.isRequired, + theme: _propTypes2.default.func.isRequired, + keyPrefix: _propTypes2.default.string.isRequired +}; +ItemsList.defaultProps = { + sectionIndex: null +}; +exports.default = ItemsList; + +/***/ }), +/* 192 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = __webpack_require__(4); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = __webpack_require__(8); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _compareObjects = __webpack_require__(44); + +var _compareObjects2 = _interopRequireDefault(_compareObjects); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var SectionTitle = function (_Component) { + _inherits(SectionTitle, _Component); + + function SectionTitle() { + _classCallCheck(this, SectionTitle); + + return _possibleConstructorReturn(this, (SectionTitle.__proto__ || Object.getPrototypeOf(SectionTitle)).apply(this, arguments)); + } + + _createClass(SectionTitle, [{ + key: 'shouldComponentUpdate', + value: function shouldComponentUpdate(nextProps) { + return (0, _compareObjects2.default)(nextProps, this.props); + } + }, { + key: 'render', + value: function render() { + var _props = this.props, + section = _props.section, + renderSectionTitle = _props.renderSectionTitle, + theme = _props.theme, + sectionKeyPrefix = _props.sectionKeyPrefix; + + var sectionTitle = renderSectionTitle(section); + + if (!sectionTitle) { + return null; + } + + return _react2.default.createElement( + 'div', + theme(sectionKeyPrefix + 'title', 'sectionTitle'), + sectionTitle + ); + } + }]); + + return SectionTitle; +}(_react.Component); + +SectionTitle.propTypes = { + section: _propTypes2.default.any.isRequired, + renderSectionTitle: _propTypes2.default.func.isRequired, + theme: _propTypes2.default.func.isRequired, + sectionKeyPrefix: _propTypes2.default.string.isRequired +}; +exports.default = SectionTitle; + +/***/ }), +/* 193 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(189).default; + +/***/ }), +/* 194 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/** @license React v16.4.1 + * react-dom.development.js + * + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + + + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +var invariant = __webpack_require__(81); +var React = __webpack_require__(4); +var warning = __webpack_require__(202); +var ExecutionEnvironment = __webpack_require__(77); +var _assign = __webpack_require__(5); +var emptyFunction = __webpack_require__(45); +var checkPropTypes = __webpack_require__(42); +var getActiveElement = __webpack_require__(80); +var shallowEqual = __webpack_require__(82); +var containsNode = __webpack_require__(78); +var emptyObject = __webpack_require__(79); +var hyphenateStyleName = __webpack_require__(199); +var camelizeStyleName = __webpack_require__(197); + +// Relying on the `invariant()` implementation lets us +// have preserve the format and params in the www builds. + +!React ? invariant(false, 'ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.') : void 0; + +var invokeGuardedCallback = function (name, func, context, a, b, c, d, e, f) { + this._hasCaughtError = false; + this._caughtError = null; + var funcArgs = Array.prototype.slice.call(arguments, 3); + try { + func.apply(context, funcArgs); + } catch (error) { + this._caughtError = error; + this._hasCaughtError = true; + } +}; + +{ + // In DEV mode, we swap out invokeGuardedCallback for a special version + // that plays more nicely with the browser's DevTools. The idea is to preserve + // "Pause on exceptions" behavior. Because React wraps all user-provided + // functions in invokeGuardedCallback, and the production version of + // invokeGuardedCallback uses a try-catch, all user exceptions are treated + // like caught exceptions, and the DevTools won't pause unless the developer + // takes the extra step of enabling pause on caught exceptions. This is + // untintuitive, though, because even though React has caught the error, from + // the developer's perspective, the error is uncaught. + // + // To preserve the expected "Pause on exceptions" behavior, we don't use a + // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake + // DOM node, and call the user-provided callback from inside an event handler + // for that fake event. If the callback throws, the error is "captured" using + // a global event handler. But because the error happens in a different + // event loop context, it does not interrupt the normal program flow. + // Effectively, this gives us try-catch behavior without actually using + // try-catch. Neat! + + // Check that the browser supports the APIs we need to implement our special + // DEV version of invokeGuardedCallback + if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { + var fakeNode = document.createElement('react'); + + var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) { + // If document doesn't exist we know for sure we will crash in this method + // when we call document.createEvent(). However this can cause confusing + // errors: https://github.com/facebookincubator/create-react-app/issues/3482 + // So we preemptively throw with a better message instead. + !(typeof document !== 'undefined') ? invariant(false, 'The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.') : void 0; + var evt = document.createEvent('Event'); + + // Keeps track of whether the user-provided callback threw an error. We + // set this to true at the beginning, then set it to false right after + // calling the function. If the function errors, `didError` will never be + // set to false. This strategy works even if the browser is flaky and + // fails to call our global error handler, because it doesn't rely on + // the error event at all. + var didError = true; + + // Create an event handler for our fake event. We will synchronously + // dispatch our fake event using `dispatchEvent`. Inside the handler, we + // call the user-provided callback. + var funcArgs = Array.prototype.slice.call(arguments, 3); + function callCallback() { + // We immediately remove the callback from event listeners so that + // nested `invokeGuardedCallback` calls do not clash. Otherwise, a + // nested call would trigger the fake event handlers of any call higher + // in the stack. + fakeNode.removeEventListener(evtType, callCallback, false); + func.apply(context, funcArgs); + didError = false; + } + + // Create a global error event handler. We use this to capture the value + // that was thrown. It's possible that this error handler will fire more + // than once; for example, if non-React code also calls `dispatchEvent` + // and a handler for that event throws. We should be resilient to most of + // those cases. Even if our error event handler fires more than once, the + // last error event is always used. If the callback actually does error, + // we know that the last error event is the correct one, because it's not + // possible for anything else to have happened in between our callback + // erroring and the code that follows the `dispatchEvent` call below. If + // the callback doesn't error, but the error event was fired, we know to + // ignore it because `didError` will be false, as described above. + var error = void 0; + // Use this to track whether the error event is ever called. + var didSetError = false; + var isCrossOriginError = false; + + function onError(event) { + error = event.error; + didSetError = true; + if (error === null && event.colno === 0 && event.lineno === 0) { + isCrossOriginError = true; + } + } + + // Create a fake event type. + var evtType = 'react-' + (name ? name : 'invokeguardedcallback'); + + // Attach our event handlers + window.addEventListener('error', onError); + fakeNode.addEventListener(evtType, callCallback, false); + + // Synchronously dispatch our fake event. If the user-provided function + // errors, it will trigger our global error handler. + evt.initEvent(evtType, false, false); + fakeNode.dispatchEvent(evt); + + if (didError) { + if (!didSetError) { + // The callback errored, but the error event never fired. + error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.'); + } else if (isCrossOriginError) { + error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.'); + } + this._hasCaughtError = true; + this._caughtError = error; + } else { + this._hasCaughtError = false; + this._caughtError = null; + } + + // Remove our event listeners + window.removeEventListener('error', onError); + }; + + invokeGuardedCallback = invokeGuardedCallbackDev; + } +} + +var invokeGuardedCallback$1 = invokeGuardedCallback; + +var ReactErrorUtils = { + // Used by Fiber to simulate a try-catch. + _caughtError: null, + _hasCaughtError: false, + + // Used by event system to capture/rethrow the first error. + _rethrowError: null, + _hasRethrowError: false, + + /** + * Call a function while guarding against errors that happens within it. + * Returns an error if it throws, otherwise null. + * + * In production, this is implemented using a try-catch. The reason we don't + * use a try-catch directly is so that we can swap out a different + * implementation in DEV mode. + * + * @param {String} name of the guard to use for logging or debugging + * @param {Function} func The function to invoke + * @param {*} context The context to use when calling the function + * @param {...*} args Arguments for function + */ + invokeGuardedCallback: function (name, func, context, a, b, c, d, e, f) { + invokeGuardedCallback$1.apply(ReactErrorUtils, arguments); + }, + + /** + * Same as invokeGuardedCallback, but instead of returning an error, it stores + * it in a global so it can be rethrown by `rethrowCaughtError` later. + * TODO: See if _caughtError and _rethrowError can be unified. + * + * @param {String} name of the guard to use for logging or debugging + * @param {Function} func The function to invoke + * @param {*} context The context to use when calling the function + * @param {...*} args Arguments for function + */ + invokeGuardedCallbackAndCatchFirstError: function (name, func, context, a, b, c, d, e, f) { + ReactErrorUtils.invokeGuardedCallback.apply(this, arguments); + if (ReactErrorUtils.hasCaughtError()) { + var error = ReactErrorUtils.clearCaughtError(); + if (!ReactErrorUtils._hasRethrowError) { + ReactErrorUtils._hasRethrowError = true; + ReactErrorUtils._rethrowError = error; + } + } + }, + + /** + * During execution of guarded functions we will capture the first error which + * we will rethrow to be handled by the top level error handler. + */ + rethrowCaughtError: function () { + return rethrowCaughtError.apply(ReactErrorUtils, arguments); + }, + + hasCaughtError: function () { + return ReactErrorUtils._hasCaughtError; + }, + + clearCaughtError: function () { + if (ReactErrorUtils._hasCaughtError) { + var error = ReactErrorUtils._caughtError; + ReactErrorUtils._caughtError = null; + ReactErrorUtils._hasCaughtError = false; + return error; + } else { + invariant(false, 'clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.'); + } + } +}; + +var rethrowCaughtError = function () { + if (ReactErrorUtils._hasRethrowError) { + var error = ReactErrorUtils._rethrowError; + ReactErrorUtils._rethrowError = null; + ReactErrorUtils._hasRethrowError = false; + throw error; + } +}; + +/** + * Injectable ordering of event plugins. + */ +var eventPluginOrder = null; + +/** + * Injectable mapping from names to event plugin modules. + */ +var namesToPlugins = {}; + +/** + * Recomputes the plugin list using the injected plugins and plugin ordering. + * + * @private + */ +function recomputePluginOrdering() { + if (!eventPluginOrder) { + // Wait until an `eventPluginOrder` is injected. + return; + } + for (var pluginName in namesToPlugins) { + var pluginModule = namesToPlugins[pluginName]; + var pluginIndex = eventPluginOrder.indexOf(pluginName); + !(pluginIndex > -1) ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : void 0; + if (plugins[pluginIndex]) { + continue; + } + !pluginModule.extractEvents ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : void 0; + plugins[pluginIndex] = pluginModule; + var publishedEvents = pluginModule.eventTypes; + for (var eventName in publishedEvents) { + !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : void 0; + } + } +} + +/** + * Publishes an event so that it can be dispatched by the supplied plugin. + * + * @param {object} dispatchConfig Dispatch configuration for the event. + * @param {object} PluginModule Plugin publishing the event. + * @return {boolean} True if the event was successfully published. + * @private + */ +function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { + !!eventNameDispatchConfigs.hasOwnProperty(eventName) ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : void 0; + eventNameDispatchConfigs[eventName] = dispatchConfig; + + var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { + for (var phaseName in phasedRegistrationNames) { + if (phasedRegistrationNames.hasOwnProperty(phaseName)) { + var phasedRegistrationName = phasedRegistrationNames[phaseName]; + publishRegistrationName(phasedRegistrationName, pluginModule, eventName); + } + } + return true; + } else if (dispatchConfig.registrationName) { + publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName); + return true; + } + return false; +} + +/** + * Publishes a registration name that is used to identify dispatched events. + * + * @param {string} registrationName Registration name to add. + * @param {object} PluginModule Plugin publishing the event. + * @private + */ +function publishRegistrationName(registrationName, pluginModule, eventName) { + !!registrationNameModules[registrationName] ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : void 0; + registrationNameModules[registrationName] = pluginModule; + registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; + + { + var lowerCasedName = registrationName.toLowerCase(); + possibleRegistrationNames[lowerCasedName] = registrationName; + + if (registrationName === 'onDoubleClick') { + possibleRegistrationNames.ondblclick = registrationName; + } + } +} + +/** + * Registers plugins so that they can extract and dispatch events. + * + * @see {EventPluginHub} + */ + +/** + * Ordered list of injected plugins. + */ +var plugins = []; + +/** + * Mapping from event name to dispatch config + */ +var eventNameDispatchConfigs = {}; + +/** + * Mapping from registration name to plugin module + */ +var registrationNameModules = {}; + +/** + * Mapping from registration name to event name + */ +var registrationNameDependencies = {}; + +/** + * Mapping from lowercase registration names to the properly cased version, + * used to warn in the case of missing event handlers. Available + * only in true. + * @type {Object} + */ +var possibleRegistrationNames = {}; +// Trust the developer to only use possibleRegistrationNames in true + +/** + * Injects an ordering of plugins (by plugin name). This allows the ordering + * to be decoupled from injection of the actual plugins so that ordering is + * always deterministic regardless of packaging, on-the-fly injection, etc. + * + * @param {array} InjectedEventPluginOrder + * @internal + * @see {EventPluginHub.injection.injectEventPluginOrder} + */ +function injectEventPluginOrder(injectedEventPluginOrder) { + !!eventPluginOrder ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : void 0; + // Clone the ordering so it cannot be dynamically mutated. + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); + recomputePluginOrdering(); +} + +/** + * Injects plugins to be used by `EventPluginHub`. The plugin names must be + * in the ordering injected by `injectEventPluginOrder`. + * + * Plugins can be injected as part of page initialization or on-the-fly. + * + * @param {object} injectedNamesToPlugins Map from names to plugin modules. + * @internal + * @see {EventPluginHub.injection.injectEventPluginsByName} + */ +function injectEventPluginsByName(injectedNamesToPlugins) { + var isOrderingDirty = false; + for (var pluginName in injectedNamesToPlugins) { + if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { + continue; + } + var pluginModule = injectedNamesToPlugins[pluginName]; + if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { + !!namesToPlugins[pluginName] ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : void 0; + namesToPlugins[pluginName] = pluginModule; + isOrderingDirty = true; + } + } + if (isOrderingDirty) { + recomputePluginOrdering(); + } +} + +var EventPluginRegistry = Object.freeze({ + plugins: plugins, + eventNameDispatchConfigs: eventNameDispatchConfigs, + registrationNameModules: registrationNameModules, + registrationNameDependencies: registrationNameDependencies, + possibleRegistrationNames: possibleRegistrationNames, + injectEventPluginOrder: injectEventPluginOrder, + injectEventPluginsByName: injectEventPluginsByName +}); + +var getFiberCurrentPropsFromNode = null; +var getInstanceFromNode = null; +var getNodeFromInstance = null; + +var injection$1 = { + injectComponentTree: function (Injected) { + getFiberCurrentPropsFromNode = Injected.getFiberCurrentPropsFromNode; + getInstanceFromNode = Injected.getInstanceFromNode; + getNodeFromInstance = Injected.getNodeFromInstance; + + { + !(getNodeFromInstance && getInstanceFromNode) ? warning(false, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; + } + } +}; + +var validateEventDispatches = void 0; +{ + validateEventDispatches = function (event) { + var dispatchListeners = event._dispatchListeners; + var dispatchInstances = event._dispatchInstances; + + var listenersIsArr = Array.isArray(dispatchListeners); + var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; + + var instancesIsArr = Array.isArray(dispatchInstances); + var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; + + !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warning(false, 'EventPluginUtils: Invalid `event`.') : void 0; + }; +} + +/** + * Dispatch the event to the listener. + * @param {SyntheticEvent} event SyntheticEvent to handle + * @param {boolean} simulated If the event is simulated (changes exn behavior) + * @param {function} listener Application-level callback + * @param {*} inst Internal component instance + */ +function executeDispatch(event, simulated, listener, inst) { + var type = event.type || 'unknown-event'; + event.currentTarget = getNodeFromInstance(inst); + ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); + event.currentTarget = null; +} + +/** + * Standard/simple iteration through an event's collected dispatches. + */ +function executeDispatchesInOrder(event, simulated) { + var dispatchListeners = event._dispatchListeners; + var dispatchInstances = event._dispatchInstances; + { + validateEventDispatches(event); + } + if (Array.isArray(dispatchListeners)) { + for (var i = 0; i < dispatchListeners.length; i++) { + if (event.isPropagationStopped()) { + break; + } + // Listeners and Instances are two parallel arrays that are always in sync. + executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); + } + } else if (dispatchListeners) { + executeDispatch(event, simulated, dispatchListeners, dispatchInstances); + } + event._dispatchListeners = null; + event._dispatchInstances = null; +} + +/** + * @see executeDispatchesInOrderStopAtTrueImpl + */ + + +/** + * Execution of a "direct" dispatch - there must be at most one dispatch + * accumulated on the event or it is considered an error. It doesn't really make + * sense for an event with multiple dispatches (bubbled) to keep track of the + * return values at each dispatch execution, but it does tend to make sense when + * dealing with "direct" dispatches. + * + * @return {*} The return value of executing the single dispatch. + */ + + +/** + * @param {SyntheticEvent} event + * @return {boolean} True iff number of dispatches accumulated is greater than 0. + */ + +/** + * Accumulates items that must not be null or undefined into the first one. This + * is used to conserve memory by avoiding array allocations, and thus sacrifices + * API cleanness. Since `current` can be null before being passed in and not + * null after this function, make sure to assign it back to `current`: + * + * `a = accumulateInto(a, b);` + * + * This API should be sparingly used. Try `accumulate` for something cleaner. + * + * @return {*|array<*>} An accumulation of items. + */ + +function accumulateInto(current, next) { + !(next != null) ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : void 0; + + if (current == null) { + return next; + } + + // Both are not empty. Warning: Never call x.concat(y) when you are not + // certain that x is an Array (x could be a string with concat method). + if (Array.isArray(current)) { + if (Array.isArray(next)) { + current.push.apply(current, next); + return current; + } + current.push(next); + return current; + } + + if (Array.isArray(next)) { + // A bit too dangerous to mutate `next`. + return [current].concat(next); + } + + return [current, next]; +} + +/** + * @param {array} arr an "accumulation" of items which is either an Array or + * a single item. Useful when paired with the `accumulate` module. This is a + * simple utility that allows us to reason about a collection of items, but + * handling the case when there is exactly one item (and we do not need to + * allocate an array). + * @param {function} cb Callback invoked with each element or a collection. + * @param {?} [scope] Scope used as `this` in a callback. + */ +function forEachAccumulated(arr, cb, scope) { + if (Array.isArray(arr)) { + arr.forEach(cb, scope); + } else if (arr) { + cb.call(scope, arr); + } +} + +/** + * Internal queue of events that have accumulated their dispatches and are + * waiting to have their dispatches executed. + */ +var eventQueue = null; + +/** + * Dispatches an event and releases it back into the pool, unless persistent. + * + * @param {?object} event Synthetic event to be dispatched. + * @param {boolean} simulated If the event is simulated (changes exn behavior) + * @private + */ +var executeDispatchesAndRelease = function (event, simulated) { + if (event) { + executeDispatchesInOrder(event, simulated); + + if (!event.isPersistent()) { + event.constructor.release(event); + } + } +}; +var executeDispatchesAndReleaseSimulated = function (e) { + return executeDispatchesAndRelease(e, true); +}; +var executeDispatchesAndReleaseTopLevel = function (e) { + return executeDispatchesAndRelease(e, false); +}; + +function isInteractive(tag) { + return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; +} + +function shouldPreventMouseEvent(name, type, props) { + switch (name) { + case 'onClick': + case 'onClickCapture': + case 'onDoubleClick': + case 'onDoubleClickCapture': + case 'onMouseDown': + case 'onMouseDownCapture': + case 'onMouseMove': + case 'onMouseMoveCapture': + case 'onMouseUp': + case 'onMouseUpCapture': + return !!(props.disabled && isInteractive(type)); + default: + return false; + } +} + +/** + * This is a unified interface for event plugins to be installed and configured. + * + * Event plugins can implement the following properties: + * + * `extractEvents` {function(string, DOMEventTarget, string, object): *} + * Required. When a top-level event is fired, this method is expected to + * extract synthetic events that will in turn be queued and dispatched. + * + * `eventTypes` {object} + * Optional, plugins that fire events must publish a mapping of registration + * names that are used to register listeners. Values of this mapping must + * be objects that contain `registrationName` or `phasedRegistrationNames`. + * + * `executeDispatch` {function(object, function, string)} + * Optional, allows plugins to override how an event gets dispatched. By + * default, the listener is simply invoked. + * + * Each plugin that is injected into `EventsPluginHub` is immediately operable. + * + * @public + */ + +/** + * Methods for injecting dependencies. + */ +var injection = { + /** + * @param {array} InjectedEventPluginOrder + * @public + */ + injectEventPluginOrder: injectEventPluginOrder, + + /** + * @param {object} injectedNamesToPlugins Map from names to plugin modules. + */ + injectEventPluginsByName: injectEventPluginsByName +}; + +/** + * @param {object} inst The instance, which is the source of events. + * @param {string} registrationName Name of listener (e.g. `onClick`). + * @return {?function} The stored callback. + */ +function getListener(inst, registrationName) { + var listener = void 0; + + // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not + // live here; needs to be moved to a better place soon + var stateNode = inst.stateNode; + if (!stateNode) { + // Work in progress (ex: onload events in incremental mode). + return null; + } + var props = getFiberCurrentPropsFromNode(stateNode); + if (!props) { + // Work in progress. + return null; + } + listener = props[registrationName]; + if (shouldPreventMouseEvent(registrationName, inst.type, props)) { + return null; + } + !(!listener || typeof listener === 'function') ? invariant(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener) : void 0; + return listener; +} + +/** + * Allows registered plugins an opportunity to extract events from top-level + * native browser events. + * + * @return {*} An accumulation of synthetic events. + * @internal + */ +function extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var events = null; + for (var i = 0; i < plugins.length; i++) { + // Not every plugin in the ordering may be loaded at runtime. + var possiblePlugin = plugins[i]; + if (possiblePlugin) { + var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); + if (extractedEvents) { + events = accumulateInto(events, extractedEvents); + } + } + } + return events; +} + +function runEventsInBatch(events, simulated) { + if (events !== null) { + eventQueue = accumulateInto(eventQueue, events); + } + + // Set `eventQueue` to null before processing it so that we can tell if more + // events get enqueued while processing. + var processingEventQueue = eventQueue; + eventQueue = null; + + if (!processingEventQueue) { + return; + } + + if (simulated) { + forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); + } else { + forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); + } + !!eventQueue ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : void 0; + // This would be a good time to rethrow if any of the event handlers threw. + ReactErrorUtils.rethrowCaughtError(); +} + +function runExtractedEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var events = extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); + runEventsInBatch(events, false); +} + +var EventPluginHub = Object.freeze({ + injection: injection, + getListener: getListener, + runEventsInBatch: runEventsInBatch, + runExtractedEventsInBatch: runExtractedEventsInBatch +}); + +var IndeterminateComponent = 0; // Before we know whether it is functional or class +var FunctionalComponent = 1; +var ClassComponent = 2; +var HostRoot = 3; // Root of a host tree. Could be nested inside another node. +var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. +var HostComponent = 5; +var HostText = 6; + + + +var Fragment = 10; +var Mode = 11; +var ContextConsumer = 12; +var ContextProvider = 13; +var ForwardRef = 14; +var Profiler = 15; +var TimeoutComponent = 16; + +var randomKey = Math.random().toString(36).slice(2); +var internalInstanceKey = '__reactInternalInstance$' + randomKey; +var internalEventHandlersKey = '__reactEventHandlers$' + randomKey; + +function precacheFiberNode(hostInst, node) { + node[internalInstanceKey] = hostInst; +} + +/** + * Given a DOM node, return the closest ReactDOMComponent or + * ReactDOMTextComponent instance ancestor. + */ +function getClosestInstanceFromNode(node) { + if (node[internalInstanceKey]) { + return node[internalInstanceKey]; + } + + while (!node[internalInstanceKey]) { + if (node.parentNode) { + node = node.parentNode; + } else { + // Top of the tree. This node must not be part of a React tree (or is + // unmounted, potentially). + return null; + } + } + + var inst = node[internalInstanceKey]; + if (inst.tag === HostComponent || inst.tag === HostText) { + // In Fiber, this will always be the deepest root. + return inst; + } + + return null; +} + +/** + * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent + * instance, or null if the node was not rendered by this React. + */ +function getInstanceFromNode$1(node) { + var inst = node[internalInstanceKey]; + if (inst) { + if (inst.tag === HostComponent || inst.tag === HostText) { + return inst; + } else { + return null; + } + } + return null; +} + +/** + * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding + * DOM node. + */ +function getNodeFromInstance$1(inst) { + if (inst.tag === HostComponent || inst.tag === HostText) { + // In Fiber this, is just the state node right now. We assume it will be + // a host component or host text. + return inst.stateNode; + } + + // Without this first invariant, passing a non-DOM-component triggers the next + // invariant for a missing parent, which is super confusing. + invariant(false, 'getNodeFromInstance: Invalid argument.'); +} + +function getFiberCurrentPropsFromNode$1(node) { + return node[internalEventHandlersKey] || null; +} + +function updateFiberProps(node, props) { + node[internalEventHandlersKey] = props; +} + +var ReactDOMComponentTree = Object.freeze({ + precacheFiberNode: precacheFiberNode, + getClosestInstanceFromNode: getClosestInstanceFromNode, + getInstanceFromNode: getInstanceFromNode$1, + getNodeFromInstance: getNodeFromInstance$1, + getFiberCurrentPropsFromNode: getFiberCurrentPropsFromNode$1, + updateFiberProps: updateFiberProps +}); + +function getParent(inst) { + do { + inst = inst.return; + // TODO: If this is a HostRoot we might want to bail out. + // That is depending on if we want nested subtrees (layers) to bubble + // events to their parent. We could also go through parentNode on the + // host node but that wouldn't work for React Native and doesn't let us + // do the portal feature. + } while (inst && inst.tag !== HostComponent); + if (inst) { + return inst; + } + return null; +} + +/** + * Return the lowest common ancestor of A and B, or null if they are in + * different trees. + */ +function getLowestCommonAncestor(instA, instB) { + var depthA = 0; + for (var tempA = instA; tempA; tempA = getParent(tempA)) { + depthA++; + } + var depthB = 0; + for (var tempB = instB; tempB; tempB = getParent(tempB)) { + depthB++; + } + + // If A is deeper, crawl up. + while (depthA - depthB > 0) { + instA = getParent(instA); + depthA--; + } + + // If B is deeper, crawl up. + while (depthB - depthA > 0) { + instB = getParent(instB); + depthB--; + } + + // Walk in lockstep until we find a match. + var depth = depthA; + while (depth--) { + if (instA === instB || instA === instB.alternate) { + return instA; + } + instA = getParent(instA); + instB = getParent(instB); + } + return null; +} + +/** + * Return if A is an ancestor of B. + */ + + +/** + * Return the parent instance of the passed-in instance. + */ +function getParentInstance(inst) { + return getParent(inst); +} + +/** + * Simulates the traversal of a two-phase, capture/bubble event dispatch. + */ +function traverseTwoPhase(inst, fn, arg) { + var path = []; + while (inst) { + path.push(inst); + inst = getParent(inst); + } + var i = void 0; + for (i = path.length; i-- > 0;) { + fn(path[i], 'captured', arg); + } + for (i = 0; i < path.length; i++) { + fn(path[i], 'bubbled', arg); + } +} + +/** + * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that + * should would receive a `mouseEnter` or `mouseLeave` event. + * + * Does not invoke the callback on the nearest common ancestor because nothing + * "entered" or "left" that element. + */ +function traverseEnterLeave(from, to, fn, argFrom, argTo) { + var common = from && to ? getLowestCommonAncestor(from, to) : null; + var pathFrom = []; + while (true) { + if (!from) { + break; + } + if (from === common) { + break; + } + var alternate = from.alternate; + if (alternate !== null && alternate === common) { + break; + } + pathFrom.push(from); + from = getParent(from); + } + var pathTo = []; + while (true) { + if (!to) { + break; + } + if (to === common) { + break; + } + var _alternate = to.alternate; + if (_alternate !== null && _alternate === common) { + break; + } + pathTo.push(to); + to = getParent(to); + } + for (var i = 0; i < pathFrom.length; i++) { + fn(pathFrom[i], 'bubbled', argFrom); + } + for (var _i = pathTo.length; _i-- > 0;) { + fn(pathTo[_i], 'captured', argTo); + } +} + +/** + * Some event types have a notion of different registration names for different + * "phases" of propagation. This finds listeners by a given phase. + */ +function listenerAtPhase(inst, event, propagationPhase) { + var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; + return getListener(inst, registrationName); +} + +/** + * A small set of propagation patterns, each of which will accept a small amount + * of information, and generate a set of "dispatch ready event objects" - which + * are sets of events that have already been annotated with a set of dispatched + * listener functions/ids. The API is designed this way to discourage these + * propagation strategies from actually executing the dispatches, since we + * always want to collect the entire set of dispatches before executing even a + * single one. + */ + +/** + * Tags a `SyntheticEvent` with dispatched listeners. Creating this function + * here, allows us to not have to bind or create functions for each event. + * Mutating the event's members allows us to not have to create a wrapping + * "dispatch" object that pairs the event with the listener. + */ +function accumulateDirectionalDispatches(inst, phase, event) { + { + !inst ? warning(false, 'Dispatching inst must not be null') : void 0; + } + var listener = listenerAtPhase(inst, event, phase); + if (listener) { + event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); + event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); + } +} + +/** + * Collect dispatches (must be entirely collected before dispatching - see unit + * tests). Lazily allocate the array to conserve memory. We must loop through + * each event and perform the traversal for each one. We cannot perform a + * single traversal for the entire collection of events because each event may + * have a different target. + */ +function accumulateTwoPhaseDispatchesSingle(event) { + if (event && event.dispatchConfig.phasedRegistrationNames) { + traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); + } +} + +/** + * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. + */ +function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { + if (event && event.dispatchConfig.phasedRegistrationNames) { + var targetInst = event._targetInst; + var parentInst = targetInst ? getParentInstance(targetInst) : null; + traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); + } +} + +/** + * Accumulates without regard to direction, does not look for phased + * registration names. Same as `accumulateDirectDispatchesSingle` but without + * requiring that the `dispatchMarker` be the same as the dispatched ID. + */ +function accumulateDispatches(inst, ignoredDirection, event) { + if (inst && event && event.dispatchConfig.registrationName) { + var registrationName = event.dispatchConfig.registrationName; + var listener = getListener(inst, registrationName); + if (listener) { + event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); + event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); + } + } +} + +/** + * Accumulates dispatches on an `SyntheticEvent`, but only for the + * `dispatchMarker`. + * @param {SyntheticEvent} event + */ +function accumulateDirectDispatchesSingle(event) { + if (event && event.dispatchConfig.registrationName) { + accumulateDispatches(event._targetInst, null, event); + } +} + +function accumulateTwoPhaseDispatches(events) { + forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); +} + +function accumulateTwoPhaseDispatchesSkipTarget(events) { + forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); +} + +function accumulateEnterLeaveDispatches(leave, enter, from, to) { + traverseEnterLeave(from, to, accumulateDispatches, leave, enter); +} + +function accumulateDirectDispatches(events) { + forEachAccumulated(events, accumulateDirectDispatchesSingle); +} + +var EventPropagators = Object.freeze({ + accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, + accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, + accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches, + accumulateDirectDispatches: accumulateDirectDispatches +}); + +// Do not uses the below two methods directly! +// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM. +// (It is the only module that is allowed to access these methods.) + +function unsafeCastStringToDOMTopLevelType(topLevelType) { + return topLevelType; +} + +function unsafeCastDOMTopLevelTypeToString(topLevelType) { + return topLevelType; +} + +/** + * Generate a mapping of standard vendor prefixes using the defined style property and event name. + * + * @param {string} styleProp + * @param {string} eventName + * @returns {object} + */ +function makePrefixMap(styleProp, eventName) { + var prefixes = {}; + + prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); + prefixes['Webkit' + styleProp] = 'webkit' + eventName; + prefixes['Moz' + styleProp] = 'moz' + eventName; + prefixes['ms' + styleProp] = 'MS' + eventName; + prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); + + return prefixes; +} + +/** + * A list of event names to a configurable list of vendor prefixes. + */ +var vendorPrefixes = { + animationend: makePrefixMap('Animation', 'AnimationEnd'), + animationiteration: makePrefixMap('Animation', 'AnimationIteration'), + animationstart: makePrefixMap('Animation', 'AnimationStart'), + transitionend: makePrefixMap('Transition', 'TransitionEnd') +}; + +/** + * Event names that have already been detected and prefixed (if applicable). + */ +var prefixedEventNames = {}; + +/** + * Element to check for prefixes on. + */ +var style = {}; + +/** + * Bootstrap if a DOM exists. + */ +if (ExecutionEnvironment.canUseDOM) { + style = document.createElement('div').style; + + // On some platforms, in particular some releases of Android 4.x, + // the un-prefixed "animation" and "transition" properties are defined on the + // style object but the events that fire will still be prefixed, so we need + // to check if the un-prefixed events are usable, and if not remove them from the map. + if (!('AnimationEvent' in window)) { + delete vendorPrefixes.animationend.animation; + delete vendorPrefixes.animationiteration.animation; + delete vendorPrefixes.animationstart.animation; + } + + // Same as above + if (!('TransitionEvent' in window)) { + delete vendorPrefixes.transitionend.transition; + } +} + +/** + * Attempts to determine the correct vendor prefixed event name. + * + * @param {string} eventName + * @returns {string} + */ +function getVendorPrefixedEventName(eventName) { + if (prefixedEventNames[eventName]) { + return prefixedEventNames[eventName]; + } else if (!vendorPrefixes[eventName]) { + return eventName; + } + + var prefixMap = vendorPrefixes[eventName]; + + for (var styleProp in prefixMap) { + if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { + return prefixedEventNames[eventName] = prefixMap[styleProp]; + } + } + + return eventName; +} + +/** + * To identify top level events in ReactDOM, we use constants defined by this + * module. This is the only module that uses the unsafe* methods to express + * that the constants actually correspond to the browser event names. This lets + * us save some bundle size by avoiding a top level type -> event name map. + * The rest of ReactDOM code should import top level types from this file. + */ +var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort'); +var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend')); +var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration')); +var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart')); +var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur'); +var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay'); +var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough'); +var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel'); +var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change'); +var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click'); +var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close'); +var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend'); +var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart'); +var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate'); +var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu'); +var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy'); +var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut'); +var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick'); +var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag'); +var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend'); +var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter'); +var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit'); +var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave'); +var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover'); +var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart'); +var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop'); +var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange'); +var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied'); +var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted'); +var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended'); +var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error'); +var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus'); +var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture'); +var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input'); +var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid'); +var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown'); +var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress'); +var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup'); +var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load'); +var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart'); +var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata'); +var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata'); +var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture'); +var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown'); +var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove'); +var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout'); +var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover'); +var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup'); +var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste'); +var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause'); +var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play'); +var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing'); +var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel'); +var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown'); + + +var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove'); +var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout'); +var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover'); +var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup'); +var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress'); +var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange'); +var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset'); +var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll'); +var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked'); +var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking'); +var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange'); +var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled'); +var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit'); +var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend'); +var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput'); +var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate'); +var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle'); +var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel'); +var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend'); +var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove'); +var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart'); +var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend')); +var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange'); +var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting'); +var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); + +// List of events that need to be individually attached to media elements. +// Note that events in this list will *not* be listened to at the top level +// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`. +var mediaEventTypes = [TOP_ABORT, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_VOLUME_CHANGE, TOP_WAITING]; + +function getRawEventName(topLevelType) { + return unsafeCastDOMTopLevelTypeToString(topLevelType); +} + +var contentKey = null; + +/** + * Gets the key used to access text content on a DOM node. + * + * @return {?string} Key used to access text content. + * @internal + */ +function getTextContentAccessor() { + if (!contentKey && ExecutionEnvironment.canUseDOM) { + // Prefer textContent to innerText because many browsers support both but + // SVG elements don't support innerText even when
does. + contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; + } + return contentKey; +} + +/** + * This helper object stores information about text content of a target node, + * allowing comparison of content before and after a given event. + * + * Identify the node where selection currently begins, then observe + * both its text content and its current position in the DOM. Since the + * browser may natively replace the target node during composition, we can + * use its position to find its replacement. + * + * + */ +var compositionState = { + _root: null, + _startText: null, + _fallbackText: null +}; + +function initialize(nativeEventTarget) { + compositionState._root = nativeEventTarget; + compositionState._startText = getText(); + return true; +} + +function reset() { + compositionState._root = null; + compositionState._startText = null; + compositionState._fallbackText = null; +} + +function getData() { + if (compositionState._fallbackText) { + return compositionState._fallbackText; + } + + var start = void 0; + var startValue = compositionState._startText; + var startLength = startValue.length; + var end = void 0; + var endValue = getText(); + var endLength = endValue.length; + + for (start = 0; start < startLength; start++) { + if (startValue[start] !== endValue[start]) { + break; + } + } + + var minEnd = startLength - start; + for (end = 1; end <= minEnd; end++) { + if (startValue[startLength - end] !== endValue[endLength - end]) { + break; + } + } + + var sliceTail = end > 1 ? 1 - end : undefined; + compositionState._fallbackText = endValue.slice(start, sliceTail); + return compositionState._fallbackText; +} + +function getText() { + if ('value' in compositionState._root) { + return compositionState._root.value; + } + return compositionState._root[getTextContentAccessor()]; +} + +/* eslint valid-typeof: 0 */ + +var didWarnForAddedNewProperty = false; +var EVENT_POOL_SIZE = 10; + +var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; + +/** + * @interface Event + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var EventInterface = { + type: null, + target: null, + // currentTarget is set when dispatching; no use in copying it here + currentTarget: emptyFunction.thatReturnsNull, + eventPhase: null, + bubbles: null, + cancelable: null, + timeStamp: function (event) { + return event.timeStamp || Date.now(); + }, + defaultPrevented: null, + isTrusted: null +}; + +/** + * Synthetic events are dispatched by event plugins, typically in response to a + * top-level event delegation handler. + * + * These systems should generally use pooling to reduce the frequency of garbage + * collection. The system should check `isPersistent` to determine whether the + * event should be released into the pool after being dispatched. Users that + * need a persisted event should invoke `persist`. + * + * Synthetic events (and subclasses) implement the DOM Level 3 Events API by + * normalizing browser quirks. Subclasses do not necessarily have to implement a + * DOM interface; custom application-specific events can also subclass this. + * + * @param {object} dispatchConfig Configuration used to dispatch this event. + * @param {*} targetInst Marker identifying the event target. + * @param {object} nativeEvent Native browser event. + * @param {DOMEventTarget} nativeEventTarget Target node. + */ +function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { + { + // these have a getter/setter for warnings + delete this.nativeEvent; + delete this.preventDefault; + delete this.stopPropagation; + } + + this.dispatchConfig = dispatchConfig; + this._targetInst = targetInst; + this.nativeEvent = nativeEvent; + + var Interface = this.constructor.Interface; + for (var propName in Interface) { + if (!Interface.hasOwnProperty(propName)) { + continue; + } + { + delete this[propName]; // this has a getter/setter for warnings + } + var normalize = Interface[propName]; + if (normalize) { + this[propName] = normalize(nativeEvent); + } else { + if (propName === 'target') { + this.target = nativeEventTarget; + } else { + this[propName] = nativeEvent[propName]; + } + } + } + + var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; + if (defaultPrevented) { + this.isDefaultPrevented = emptyFunction.thatReturnsTrue; + } else { + this.isDefaultPrevented = emptyFunction.thatReturnsFalse; + } + this.isPropagationStopped = emptyFunction.thatReturnsFalse; + return this; +} + +_assign(SyntheticEvent.prototype, { + preventDefault: function () { + this.defaultPrevented = true; + var event = this.nativeEvent; + if (!event) { + return; + } + + if (event.preventDefault) { + event.preventDefault(); + } else if (typeof event.returnValue !== 'unknown') { + event.returnValue = false; + } + this.isDefaultPrevented = emptyFunction.thatReturnsTrue; + }, + + stopPropagation: function () { + var event = this.nativeEvent; + if (!event) { + return; + } + + if (event.stopPropagation) { + event.stopPropagation(); + } else if (typeof event.cancelBubble !== 'unknown') { + // The ChangeEventPlugin registers a "propertychange" event for + // IE. This event does not support bubbling or cancelling, and + // any references to cancelBubble throw "Member not found". A + // typeof check of "unknown" circumvents this issue (and is also + // IE specific). + event.cancelBubble = true; + } + + this.isPropagationStopped = emptyFunction.thatReturnsTrue; + }, + + /** + * We release all dispatched `SyntheticEvent`s after each event loop, adding + * them back into the pool. This allows a way to hold onto a reference that + * won't be added back into the pool. + */ + persist: function () { + this.isPersistent = emptyFunction.thatReturnsTrue; + }, + + /** + * Checks if this event should be released back into the pool. + * + * @return {boolean} True if this should not be released, false otherwise. + */ + isPersistent: emptyFunction.thatReturnsFalse, + + /** + * `PooledClass` looks for `destructor` on each instance it releases. + */ + destructor: function () { + var Interface = this.constructor.Interface; + for (var propName in Interface) { + { + Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); + } + } + for (var i = 0; i < shouldBeReleasedProperties.length; i++) { + this[shouldBeReleasedProperties[i]] = null; + } + { + Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); + Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction)); + Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)); + } + } +}); + +SyntheticEvent.Interface = EventInterface; + +/** + * Helper to reduce boilerplate when creating subclasses. + */ +SyntheticEvent.extend = function (Interface) { + var Super = this; + + var E = function () {}; + E.prototype = Super.prototype; + var prototype = new E(); + + function Class() { + return Super.apply(this, arguments); + } + _assign(prototype, Class.prototype); + Class.prototype = prototype; + Class.prototype.constructor = Class; + + Class.Interface = _assign({}, Super.Interface, Interface); + Class.extend = Super.extend; + addEventPoolingTo(Class); + + return Class; +}; + +/** Proxying after everything set on SyntheticEvent + * to resolve Proxy issue on some WebKit browsers + * in which some Event properties are set to undefined (GH#10010) + */ +{ + var isProxySupported = typeof Proxy === 'function' && + // https://github.com/facebook/react/issues/12011 + !Object.isSealed(new Proxy({}, {})); + + if (isProxySupported) { + /*eslint-disable no-func-assign */ + SyntheticEvent = new Proxy(SyntheticEvent, { + construct: function (target, args) { + return this.apply(target, Object.create(target.prototype), args); + }, + apply: function (constructor, that, args) { + return new Proxy(constructor.apply(that, args), { + set: function (target, prop, value) { + if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { + !(didWarnForAddedNewProperty || target.isPersistent()) ? warning(false, "This synthetic event is reused for performance reasons. If you're " + "seeing this, you're adding a new property in the synthetic event object. " + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0; + didWarnForAddedNewProperty = true; + } + target[prop] = value; + return true; + } + }); + } + }); + /*eslint-enable no-func-assign */ + } +} + +addEventPoolingTo(SyntheticEvent); + +/** + * Helper to nullify syntheticEvent instance properties when destructing + * + * @param {String} propName + * @param {?object} getVal + * @return {object} defineProperty object + */ +function getPooledWarningPropertyDefinition(propName, getVal) { + var isFunction = typeof getVal === 'function'; + return { + configurable: true, + set: set, + get: get + }; + + function set(val) { + var action = isFunction ? 'setting the method' : 'setting the property'; + warn(action, 'This is effectively a no-op'); + return val; + } + + function get() { + var action = isFunction ? 'accessing the method' : 'accessing the property'; + var result = isFunction ? 'This is a no-op function' : 'This is set to null'; + warn(action, result); + return getVal; + } + + function warn(action, result) { + var warningCondition = false; + !warningCondition ? warning(false, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; + } +} + +function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { + var EventConstructor = this; + if (EventConstructor.eventPool.length) { + var instance = EventConstructor.eventPool.pop(); + EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst); + return instance; + } + return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst); +} + +function releasePooledEvent(event) { + var EventConstructor = this; + !(event instanceof EventConstructor) ? invariant(false, 'Trying to release an event instance into a pool of a different type.') : void 0; + event.destructor(); + if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { + EventConstructor.eventPool.push(event); + } +} + +function addEventPoolingTo(EventConstructor) { + EventConstructor.eventPool = []; + EventConstructor.getPooled = getPooledEvent; + EventConstructor.release = releasePooledEvent; +} + +var SyntheticEvent$1 = SyntheticEvent; + +/** + * @interface Event + * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents + */ +var SyntheticCompositionEvent = SyntheticEvent$1.extend({ + data: null +}); + +/** + * @interface Event + * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 + * /#events-inputevents + */ +var SyntheticInputEvent = SyntheticEvent$1.extend({ + data: null +}); + +var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space +var START_KEYCODE = 229; + +var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; + +var documentMode = null; +if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { + documentMode = document.documentMode; +} + +// Webkit offers a very useful `textInput` event that can be used to +// directly represent `beforeInput`. The IE `textinput` event is not as +// useful, so we don't use it. +var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode; + +// In IE9+, we have access to composition events, but the data supplied +// by the native compositionend event may be incorrect. Japanese ideographic +// spaces, for instance (\u3000) are not recorded correctly. +var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); + +var SPACEBAR_CODE = 32; +var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); + +// Events and their corresponding property names. +var eventTypes = { + beforeInput: { + phasedRegistrationNames: { + bubbled: 'onBeforeInput', + captured: 'onBeforeInputCapture' + }, + dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE] + }, + compositionEnd: { + phasedRegistrationNames: { + bubbled: 'onCompositionEnd', + captured: 'onCompositionEndCapture' + }, + dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN] + }, + compositionStart: { + phasedRegistrationNames: { + bubbled: 'onCompositionStart', + captured: 'onCompositionStartCapture' + }, + dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN] + }, + compositionUpdate: { + phasedRegistrationNames: { + bubbled: 'onCompositionUpdate', + captured: 'onCompositionUpdateCapture' + }, + dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN] + } +}; + +// Track whether we've ever handled a keypress on the space key. +var hasSpaceKeypress = false; + +/** + * Return whether a native keypress event is assumed to be a command. + * This is required because Firefox fires `keypress` events for key commands + * (cut, copy, select-all, etc.) even though no character is inserted. + */ +function isKeypressCommand(nativeEvent) { + return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && + // ctrlKey && altKey is equivalent to AltGr, and is not a command. + !(nativeEvent.ctrlKey && nativeEvent.altKey); +} + +/** + * Translate native top level events into event types. + * + * @param {string} topLevelType + * @return {object} + */ +function getCompositionEventType(topLevelType) { + switch (topLevelType) { + case TOP_COMPOSITION_START: + return eventTypes.compositionStart; + case TOP_COMPOSITION_END: + return eventTypes.compositionEnd; + case TOP_COMPOSITION_UPDATE: + return eventTypes.compositionUpdate; + } +} + +/** + * Does our fallback best-guess model think this event signifies that + * composition has begun? + * + * @param {string} topLevelType + * @param {object} nativeEvent + * @return {boolean} + */ +function isFallbackCompositionStart(topLevelType, nativeEvent) { + return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE; +} + +/** + * Does our fallback mode think that this event is the end of composition? + * + * @param {string} topLevelType + * @param {object} nativeEvent + * @return {boolean} + */ +function isFallbackCompositionEnd(topLevelType, nativeEvent) { + switch (topLevelType) { + case TOP_KEY_UP: + // Command keys insert or clear IME input. + return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; + case TOP_KEY_DOWN: + // Expect IME keyCode on each keydown. If we get any other + // code we must have exited earlier. + return nativeEvent.keyCode !== START_KEYCODE; + case TOP_KEY_PRESS: + case TOP_MOUSE_DOWN: + case TOP_BLUR: + // Events are not possible without cancelling IME. + return true; + default: + return false; + } +} + +/** + * Google Input Tools provides composition data via a CustomEvent, + * with the `data` property populated in the `detail` object. If this + * is available on the event object, use it. If not, this is a plain + * composition event and we have nothing special to extract. + * + * @param {object} nativeEvent + * @return {?string} + */ +function getDataFromCustomEvent(nativeEvent) { + var detail = nativeEvent.detail; + if (typeof detail === 'object' && 'data' in detail) { + return detail.data; + } + return null; +} + +// Track the current IME composition status, if any. +var isComposing = false; + +/** + * @return {?object} A SyntheticCompositionEvent. + */ +function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var eventType = void 0; + var fallbackData = void 0; + + if (canUseCompositionEvent) { + eventType = getCompositionEventType(topLevelType); + } else if (!isComposing) { + if (isFallbackCompositionStart(topLevelType, nativeEvent)) { + eventType = eventTypes.compositionStart; + } + } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { + eventType = eventTypes.compositionEnd; + } + + if (!eventType) { + return null; + } + + if (useFallbackCompositionData) { + // The current composition is stored statically and must not be + // overwritten while composition continues. + if (!isComposing && eventType === eventTypes.compositionStart) { + isComposing = initialize(nativeEventTarget); + } else if (eventType === eventTypes.compositionEnd) { + if (isComposing) { + fallbackData = getData(); + } + } + } + + var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); + + if (fallbackData) { + // Inject data generated from fallback path into the synthetic event. + // This matches the property of native CompositionEventInterface. + event.data = fallbackData; + } else { + var customData = getDataFromCustomEvent(nativeEvent); + if (customData !== null) { + event.data = customData; + } + } + + accumulateTwoPhaseDispatches(event); + return event; +} + +/** + * @param {TopLevelType} topLevelType Number from `TopLevelType`. + * @param {object} nativeEvent Native browser event. + * @return {?string} The string corresponding to this `beforeInput` event. + */ +function getNativeBeforeInputChars(topLevelType, nativeEvent) { + switch (topLevelType) { + case TOP_COMPOSITION_END: + return getDataFromCustomEvent(nativeEvent); + case TOP_KEY_PRESS: + /** + * If native `textInput` events are available, our goal is to make + * use of them. However, there is a special case: the spacebar key. + * In Webkit, preventing default on a spacebar `textInput` event + * cancels character insertion, but it *also* causes the browser + * to fall back to its default spacebar behavior of scrolling the + * page. + * + * Tracking at: + * https://code.google.com/p/chromium/issues/detail?id=355103 + * + * To avoid this issue, use the keypress event as if no `textInput` + * event is available. + */ + var which = nativeEvent.which; + if (which !== SPACEBAR_CODE) { + return null; + } + + hasSpaceKeypress = true; + return SPACEBAR_CHAR; + + case TOP_TEXT_INPUT: + // Record the characters to be added to the DOM. + var chars = nativeEvent.data; + + // If it's a spacebar character, assume that we have already handled + // it at the keypress level and bail immediately. Android Chrome + // doesn't give us keycodes, so we need to blacklist it. + if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { + return null; + } + + return chars; + + default: + // For other native event types, do nothing. + return null; + } +} + +/** + * For browsers that do not provide the `textInput` event, extract the + * appropriate string to use for SyntheticInputEvent. + * + * @param {number} topLevelType Number from `TopLevelEventTypes`. + * @param {object} nativeEvent Native browser event. + * @return {?string} The fallback string for this `beforeInput` event. + */ +function getFallbackBeforeInputChars(topLevelType, nativeEvent) { + // If we are currently composing (IME) and using a fallback to do so, + // try to extract the composed characters from the fallback object. + // If composition event is available, we extract a string only at + // compositionevent, otherwise extract it at fallback events. + if (isComposing) { + if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) { + var chars = getData(); + reset(); + isComposing = false; + return chars; + } + return null; + } + + switch (topLevelType) { + case TOP_PASTE: + // If a paste event occurs after a keypress, throw out the input + // chars. Paste events should not lead to BeforeInput events. + return null; + case TOP_KEY_PRESS: + /** + * As of v27, Firefox may fire keypress events even when no character + * will be inserted. A few possibilities: + * + * - `which` is `0`. Arrow keys, Esc key, etc. + * + * - `which` is the pressed key code, but no char is available. + * Ex: 'AltGr + d` in Polish. There is no modified character for + * this key combination and no character is inserted into the + * document, but FF fires the keypress for char code `100` anyway. + * No `input` event will occur. + * + * - `which` is the pressed key code, but a command combination is + * being used. Ex: `Cmd+C`. No character is inserted, and no + * `input` event will occur. + */ + if (!isKeypressCommand(nativeEvent)) { + // IE fires the `keypress` event when a user types an emoji via + // Touch keyboard of Windows. In such a case, the `char` property + // holds an emoji character like `\uD83D\uDE0A`. Because its length + // is 2, the property `which` does not represent an emoji correctly. + // In such a case, we directly return the `char` property instead of + // using `which`. + if (nativeEvent.char && nativeEvent.char.length > 1) { + return nativeEvent.char; + } else if (nativeEvent.which) { + return String.fromCharCode(nativeEvent.which); + } + } + return null; + case TOP_COMPOSITION_END: + return useFallbackCompositionData ? null : nativeEvent.data; + default: + return null; + } +} + +/** + * Extract a SyntheticInputEvent for `beforeInput`, based on either native + * `textInput` or fallback behavior. + * + * @return {?object} A SyntheticInputEvent. + */ +function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var chars = void 0; + + if (canUseTextInputEvent) { + chars = getNativeBeforeInputChars(topLevelType, nativeEvent); + } else { + chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); + } + + // If no characters are being inserted, no BeforeInput event should + // be fired. + if (!chars) { + return null; + } + + var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); + + event.data = chars; + accumulateTwoPhaseDispatches(event); + return event; +} + +/** + * Create an `onBeforeInput` event to match + * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. + * + * This event plugin is based on the native `textInput` event + * available in Chrome, Safari, Opera, and IE. This event fires after + * `onKeyPress` and `onCompositionEnd`, but before `onInput`. + * + * `beforeInput` is spec'd but not implemented in any browsers, and + * the `input` event does not provide any useful information about what has + * actually been added, contrary to the spec. Thus, `textInput` is the best + * available event to identify the characters that have actually been inserted + * into the target node. + * + * This plugin is also responsible for emitting `composition` events, thus + * allowing us to share composition fallback code for both `beforeInput` and + * `composition` event types. + */ +var BeforeInputEventPlugin = { + eventTypes: eventTypes, + + extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget); + + var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget); + + if (composition === null) { + return beforeInput; + } + + if (beforeInput === null) { + return composition; + } + + return [composition, beforeInput]; + } +}; + +// Use to restore controlled state after a change event has fired. + +var fiberHostComponent = null; + +var ReactControlledComponentInjection = { + injectFiberControlledHostComponent: function (hostComponentImpl) { + // The fiber implementation doesn't use dynamic dispatch so we need to + // inject the implementation. + fiberHostComponent = hostComponentImpl; + } +}; + +var restoreTarget = null; +var restoreQueue = null; + +function restoreStateOfTarget(target) { + // We perform this translation at the end of the event loop so that we + // always receive the correct fiber here + var internalInstance = getInstanceFromNode(target); + if (!internalInstance) { + // Unmounted + return; + } + !(fiberHostComponent && typeof fiberHostComponent.restoreControlledState === 'function') ? invariant(false, 'Fiber needs to be injected to handle a fiber target for controlled events. This error is likely caused by a bug in React. Please file an issue.') : void 0; + var props = getFiberCurrentPropsFromNode(internalInstance.stateNode); + fiberHostComponent.restoreControlledState(internalInstance.stateNode, internalInstance.type, props); +} + +var injection$2 = ReactControlledComponentInjection; + +function enqueueStateRestore(target) { + if (restoreTarget) { + if (restoreQueue) { + restoreQueue.push(target); + } else { + restoreQueue = [target]; + } + } else { + restoreTarget = target; + } +} + +function needsStateRestore() { + return restoreTarget !== null || restoreQueue !== null; +} + +function restoreStateIfNeeded() { + if (!restoreTarget) { + return; + } + var target = restoreTarget; + var queuedTargets = restoreQueue; + restoreTarget = null; + restoreQueue = null; + + restoreStateOfTarget(target); + if (queuedTargets) { + for (var i = 0; i < queuedTargets.length; i++) { + restoreStateOfTarget(queuedTargets[i]); + } + } +} + +var ReactControlledComponent = Object.freeze({ + injection: injection$2, + enqueueStateRestore: enqueueStateRestore, + needsStateRestore: needsStateRestore, + restoreStateIfNeeded: restoreStateIfNeeded +}); + +// Used as a way to call batchedUpdates when we don't have a reference to +// the renderer. Such as when we're dispatching events or if third party +// libraries need to call batchedUpdates. Eventually, this API will go away when +// everything is batched by default. We'll then have a similar API to opt-out of +// scheduled work and instead do synchronous work. + +// Defaults +var _batchedUpdates = function (fn, bookkeeping) { + return fn(bookkeeping); +}; +var _interactiveUpdates = function (fn, a, b) { + return fn(a, b); +}; +var _flushInteractiveUpdates = function () {}; + +var isBatching = false; +function batchedUpdates(fn, bookkeeping) { + if (isBatching) { + // If we are currently inside another batch, we need to wait until it + // fully completes before restoring state. + return fn(bookkeeping); + } + isBatching = true; + try { + return _batchedUpdates(fn, bookkeeping); + } finally { + // Here we wait until all updates have propagated, which is important + // when using controlled components within layers: + // https://github.com/facebook/react/issues/1698 + // Then we restore state of any controlled component. + isBatching = false; + var controlledComponentsHavePendingUpdates = needsStateRestore(); + if (controlledComponentsHavePendingUpdates) { + // If a controlled event was fired, we may need to restore the state of + // the DOM node back to the controlled value. This is necessary when React + // bails out of the update without touching the DOM. + _flushInteractiveUpdates(); + restoreStateIfNeeded(); + } + } +} + +function interactiveUpdates(fn, a, b) { + return _interactiveUpdates(fn, a, b); +} + + + +var injection$3 = { + injectRenderer: function (renderer) { + _batchedUpdates = renderer.batchedUpdates; + _interactiveUpdates = renderer.interactiveUpdates; + _flushInteractiveUpdates = renderer.flushInteractiveUpdates; + } +}; + +/** + * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary + */ +var supportedInputTypes = { + color: true, + date: true, + datetime: true, + 'datetime-local': true, + email: true, + month: true, + number: true, + password: true, + range: true, + search: true, + tel: true, + text: true, + time: true, + url: true, + week: true +}; + +function isTextInputElement(elem) { + var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); + + if (nodeName === 'input') { + return !!supportedInputTypes[elem.type]; + } + + if (nodeName === 'textarea') { + return true; + } + + return false; +} + +/** + * HTML nodeType values that represent the type of the node + */ + +var ELEMENT_NODE = 1; +var TEXT_NODE = 3; +var COMMENT_NODE = 8; +var DOCUMENT_NODE = 9; +var DOCUMENT_FRAGMENT_NODE = 11; + +/** + * Gets the target node from a native browser event by accounting for + * inconsistencies in browser DOM APIs. + * + * @param {object} nativeEvent Native browser event. + * @return {DOMEventTarget} Target node. + */ +function getEventTarget(nativeEvent) { + // Fallback to nativeEvent.srcElement for IE9 + // https://github.com/facebook/react/issues/12506 + var target = nativeEvent.target || nativeEvent.srcElement || window; + + // Normalize SVG element events #4963 + if (target.correspondingUseElement) { + target = target.correspondingUseElement; + } + + // Safari may fire events on text nodes (Node.TEXT_NODE is 3). + // @see http://www.quirksmode.org/js/events_properties.html + return target.nodeType === TEXT_NODE ? target.parentNode : target; +} + +/** + * Checks if an event is supported in the current execution environment. + * + * NOTE: This will not work correctly for non-generic events such as `change`, + * `reset`, `load`, `error`, and `select`. + * + * Borrows from Modernizr. + * + * @param {string} eventNameSuffix Event name, e.g. "click". + * @param {?boolean} capture Check if the capture phase is supported. + * @return {boolean} True if the event is supported. + * @internal + * @license Modernizr 3.0.0pre (Custom Build) | MIT + */ +function isEventSupported(eventNameSuffix, capture) { + if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { + return false; + } + + var eventName = 'on' + eventNameSuffix; + var isSupported = eventName in document; + + if (!isSupported) { + var element = document.createElement('div'); + element.setAttribute(eventName, 'return;'); + isSupported = typeof element[eventName] === 'function'; + } + + return isSupported; +} + +function isCheckable(elem) { + var type = elem.type; + var nodeName = elem.nodeName; + return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio'); +} + +function getTracker(node) { + return node._valueTracker; +} + +function detachTracker(node) { + node._valueTracker = null; +} + +function getValueFromNode(node) { + var value = ''; + if (!node) { + return value; + } + + if (isCheckable(node)) { + value = node.checked ? 'true' : 'false'; + } else { + value = node.value; + } + + return value; +} + +function trackValueOnNode(node) { + var valueField = isCheckable(node) ? 'checked' : 'value'; + var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); + + var currentValue = '' + node[valueField]; + + // if someone has already defined a value or Safari, then bail + // and don't track value will cause over reporting of changes, + // but it's better then a hard failure + // (needed for certain tests that spyOn input values and Safari) + if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') { + return; + } + var get = descriptor.get, + set = descriptor.set; + + Object.defineProperty(node, valueField, { + configurable: true, + get: function () { + return get.call(this); + }, + set: function (value) { + currentValue = '' + value; + set.call(this, value); + } + }); + // We could've passed this the first time + // but it triggers a bug in IE11 and Edge 14/15. + // Calling defineProperty() again should be equivalent. + // https://github.com/facebook/react/issues/11768 + Object.defineProperty(node, valueField, { + enumerable: descriptor.enumerable + }); + + var tracker = { + getValue: function () { + return currentValue; + }, + setValue: function (value) { + currentValue = '' + value; + }, + stopTracking: function () { + detachTracker(node); + delete node[valueField]; + } + }; + return tracker; +} + +function track(node) { + if (getTracker(node)) { + return; + } + + // TODO: Once it's just Fiber we can move this to node._wrapperState + node._valueTracker = trackValueOnNode(node); +} + +function updateValueIfChanged(node) { + if (!node) { + return false; + } + + var tracker = getTracker(node); + // if there is no tracker at this point it's unlikely + // that trying again will succeed + if (!tracker) { + return true; + } + + var lastValue = tracker.getValue(); + var nextValue = getValueFromNode(node); + if (nextValue !== lastValue) { + tracker.setValue(nextValue); + return true; + } + return false; +} + +var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ReactCurrentOwner = ReactInternals.ReactCurrentOwner; +var ReactDebugCurrentFrame = ReactInternals.ReactDebugCurrentFrame; + +var describeComponentFrame = function (name, source, ownerName) { + return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : ''); +}; + +// The Symbol used to tag the ReactElement-like types. If there is no native Symbol +// nor polyfill, then a plain number is used for performance. +var hasSymbol = typeof Symbol === 'function' && Symbol.for; + +var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; +var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; +var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; +var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; +var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; +var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; +var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; +var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf; +var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; +var REACT_TIMEOUT_TYPE = hasSymbol ? Symbol.for('react.timeout') : 0xead1; + +var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; + +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable === 'undefined') { + return null; + } + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + return null; +} + +function getComponentName(fiber) { + var type = fiber.type; + + if (typeof type === 'function') { + return type.displayName || type.name; + } + if (typeof type === 'string') { + return type; + } + switch (type) { + case REACT_ASYNC_MODE_TYPE: + return 'AsyncMode'; + case REACT_CONTEXT_TYPE: + return 'Context.Consumer'; + case REACT_FRAGMENT_TYPE: + return 'ReactFragment'; + case REACT_PORTAL_TYPE: + return 'ReactPortal'; + case REACT_PROFILER_TYPE: + return 'Profiler(' + fiber.pendingProps.id + ')'; + case REACT_PROVIDER_TYPE: + return 'Context.Provider'; + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + case REACT_TIMEOUT_TYPE: + return 'Timeout'; + } + if (typeof type === 'object' && type !== null) { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + var functionName = type.render.displayName || type.render.name || ''; + return functionName !== '' ? 'ForwardRef(' + functionName + ')' : 'ForwardRef'; + } + } + return null; +} + +function describeFiber(fiber) { + switch (fiber.tag) { + case IndeterminateComponent: + case FunctionalComponent: + case ClassComponent: + case HostComponent: + var owner = fiber._debugOwner; + var source = fiber._debugSource; + var name = getComponentName(fiber); + var ownerName = null; + if (owner) { + ownerName = getComponentName(owner); + } + return describeComponentFrame(name, source, ownerName); + default: + return ''; + } +} + +// This function can only be called with a work-in-progress fiber and +// only during begin or complete phase. Do not call it under any other +// circumstances. +function getStackAddendumByWorkInProgressFiber(workInProgress) { + var info = ''; + var node = workInProgress; + do { + info += describeFiber(node); + // Otherwise this return pointer might point to the wrong tree: + node = node.return; + } while (node); + return info; +} + +function getCurrentFiberOwnerName$1() { + { + var fiber = ReactDebugCurrentFiber.current; + if (fiber === null) { + return null; + } + var owner = fiber._debugOwner; + if (owner !== null && typeof owner !== 'undefined') { + return getComponentName(owner); + } + } + return null; +} + +function getCurrentFiberStackAddendum$1() { + { + var fiber = ReactDebugCurrentFiber.current; + if (fiber === null) { + return null; + } + // Safe because if current fiber exists, we are reconciling, + // and it is guaranteed to be the work-in-progress version. + return getStackAddendumByWorkInProgressFiber(fiber); + } + return null; +} + +function resetCurrentFiber() { + ReactDebugCurrentFrame.getCurrentStack = null; + ReactDebugCurrentFiber.current = null; + ReactDebugCurrentFiber.phase = null; +} + +function setCurrentFiber(fiber) { + ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackAddendum$1; + ReactDebugCurrentFiber.current = fiber; + ReactDebugCurrentFiber.phase = null; +} + +function setCurrentPhase(phase) { + ReactDebugCurrentFiber.phase = phase; +} + +var ReactDebugCurrentFiber = { + current: null, + phase: null, + resetCurrentFiber: resetCurrentFiber, + setCurrentFiber: setCurrentFiber, + setCurrentPhase: setCurrentPhase, + getCurrentFiberOwnerName: getCurrentFiberOwnerName$1, + getCurrentFiberStackAddendum: getCurrentFiberStackAddendum$1 +}; + +// A reserved attribute. +// It is handled by React separately and shouldn't be written to the DOM. +var RESERVED = 0; + +// A simple string attribute. +// Attributes that aren't in the whitelist are presumed to have this type. +var STRING = 1; + +// A string attribute that accepts booleans in React. In HTML, these are called +// "enumerated" attributes with "true" and "false" as possible values. +// When true, it should be set to a "true" string. +// When false, it should be set to a "false" string. +var BOOLEANISH_STRING = 2; + +// A real boolean attribute. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. +var BOOLEAN = 3; + +// An attribute that can be used as a flag as well as with a value. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. +// For any other value, should be present with that value. +var OVERLOADED_BOOLEAN = 4; + +// An attribute that must be numeric or parse as a numeric. +// When falsy, it should be removed. +var NUMERIC = 5; + +// An attribute that must be positive numeric or parse as a positive numeric. +// When falsy, it should be removed. +var POSITIVE_NUMERIC = 6; + +/* eslint-disable max-len */ +var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; +/* eslint-enable max-len */ +var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; + + +var ROOT_ATTRIBUTE_NAME = 'data-reactroot'; +var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); + +var illegalAttributeNameCache = {}; +var validatedAttributeNameCache = {}; + +function isAttributeNameSafe(attributeName) { + if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { + return true; + } + if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { + return false; + } + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } + illegalAttributeNameCache[attributeName] = true; + { + warning(false, 'Invalid attribute name: `%s`', attributeName); + } + return false; +} + +function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null) { + return propertyInfo.type === RESERVED; + } + if (isCustomComponentTag) { + return false; + } + if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) { + return true; + } + return false; +} + +function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null && propertyInfo.type === RESERVED) { + return false; + } + switch (typeof value) { + case 'function': + // $FlowIssue symbol is perfectly valid here + case 'symbol': + // eslint-disable-line + return true; + case 'boolean': + { + if (isCustomComponentTag) { + return false; + } + if (propertyInfo !== null) { + return !propertyInfo.acceptsBooleans; + } else { + var prefix = name.toLowerCase().slice(0, 5); + return prefix !== 'data-' && prefix !== 'aria-'; + } + } + default: + return false; + } +} + +function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { + if (value === null || typeof value === 'undefined') { + return true; + } + if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { + return true; + } + if (isCustomComponentTag) { + return false; + } + if (propertyInfo !== null) { + switch (propertyInfo.type) { + case BOOLEAN: + return !value; + case OVERLOADED_BOOLEAN: + return value === false; + case NUMERIC: + return isNaN(value); + case POSITIVE_NUMERIC: + return isNaN(value) || value < 1; + } + } + return false; +} + +function getPropertyInfo(name) { + return properties.hasOwnProperty(name) ? properties[name] : null; +} + +function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace) { + this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; + this.attributeName = attributeName; + this.attributeNamespace = attributeNamespace; + this.mustUseProperty = mustUseProperty; + this.propertyName = name; + this.type = type; +} + +// When adding attributes to this list, be sure to also add them to +// the `possibleStandardNames` module to ensure casing and incorrect +// name warnings. +var properties = {}; + +// These props are reserved by React. They shouldn't be written to the DOM. +['children', 'dangerouslySetInnerHTML', +// TODO: This prevents the assignment of defaultValue to regular +// elements (not just inputs). Now that ReactDOMInput assigns to the +// defaultValue property -- do we need this? +'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty + name, // attributeName + null); +} // attributeNamespace +); + +// A few React string attributes have a different name. +// This is a mapping from React prop names to the attribute names. +[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { + var name = _ref[0], + attributeName = _ref[1]; + + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, // attributeName + null); +} // attributeNamespace +); + +// These are "enumerated" HTML attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). +['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name.toLowerCase(), // attributeName + null); +} // attributeNamespace +); + +// These are "enumerated" SVG attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). +// Since these are SVG attributes, their attribute names are case-sensitive. +['autoReverse', 'externalResourcesRequired', 'preserveAlpha'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name, // attributeName + null); +} // attributeNamespace +); + +// These are HTML boolean attributes. +['allowFullScreen', 'async', +// Note: there is a special case that prevents it from being written to the DOM +// on the client side because the browsers are inconsistent. Instead we call focus(). +'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', +// Microdata +'itemScope'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty + name.toLowerCase(), // attributeName + null); +} // attributeNamespace +); + +// These are the few React props that we set as DOM properties +// rather than attributes. These are all booleans. +['checked', +// Note: `option.selected` is not updated if `select.multiple` is +// disabled with `removeAttribute`. We have special logic for handling this. +'multiple', 'muted', 'selected'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty + name.toLowerCase(), // attributeName + null); +} // attributeNamespace +); + +// These are HTML attributes that are "overloaded booleans": they behave like +// booleans, but can also accept a string value. +['capture', 'download'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty + name.toLowerCase(), // attributeName + null); +} // attributeNamespace +); + +// These are HTML attributes that must be positive numbers. +['cols', 'rows', 'size', 'span'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty + name.toLowerCase(), // attributeName + null); +} // attributeNamespace +); + +// These are HTML attributes that must be numbers. +['rowSpan', 'start'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty + name.toLowerCase(), // attributeName + null); +} // attributeNamespace +); + +var CAMELIZE = /[\-\:]([a-z])/g; +var capitalize = function (token) { + return token[1].toUpperCase(); +}; + +// This is a list of all SVG attributes that need special casing, namespacing, +// or boolean value assignment. Regular attributes that just accept strings +// and have the same names are omitted, just like in the HTML whitelist. +// Some of these attributes can be hard to find. This list was created by +// scrapping the MDN documentation. +['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height'].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, null); +} // attributeNamespace +); + +// String SVG attributes with the xlink namespace. +['xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type'].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/1999/xlink'); +}); + +// String SVG attributes with the xml namespace. +['xml:base', 'xml:lang', 'xml:space'].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/XML/1998/namespace'); +}); + +// Special case: this attribute exists both in HTML and SVG. +// Its "tabindex" attribute name is case-sensitive in SVG so we can't just use +// its React `tabIndex` name, like we do for attributes that exist only in HTML. +properties.tabIndex = new PropertyInfoRecord('tabIndex', STRING, false, // mustUseProperty +'tabindex', // attributeName +null); + +/** + * Get the value for a property on a node. Only used in DEV for SSR validation. + * The "expected" argument is used as a hint of what the expected value is. + * Some properties have multiple equivalent values. + */ +function getValueForProperty(node, name, expected, propertyInfo) { + { + if (propertyInfo.mustUseProperty) { + var propertyName = propertyInfo.propertyName; + + return node[propertyName]; + } else { + var attributeName = propertyInfo.attributeName; + + var stringValue = null; + + if (propertyInfo.type === OVERLOADED_BOOLEAN) { + if (node.hasAttribute(attributeName)) { + var value = node.getAttribute(attributeName); + if (value === '') { + return true; + } + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return value; + } + if (value === '' + expected) { + return expected; + } + return value; + } + } else if (node.hasAttribute(attributeName)) { + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + // We had an attribute but shouldn't have had one, so read it + // for the error message. + return node.getAttribute(attributeName); + } + if (propertyInfo.type === BOOLEAN) { + // If this was a boolean, it doesn't matter what the value is + // the fact that we have it is the same as the expected. + return expected; + } + // Even if this property uses a namespace we use getAttribute + // because we assume its namespaced name is the same as our config. + // To use getAttributeNS we need the local name which we don't have + // in our config atm. + stringValue = node.getAttribute(attributeName); + } + + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return stringValue === null ? expected : stringValue; + } else if (stringValue === '' + expected) { + return expected; + } else { + return stringValue; + } + } + } +} + +/** + * Get the value for a attribute on a node. Only used in DEV for SSR validation. + * The third argument is used as a hint of what the expected value is. Some + * attributes have multiple equivalent values. + */ +function getValueForAttribute(node, name, expected) { + { + if (!isAttributeNameSafe(name)) { + return; + } + if (!node.hasAttribute(name)) { + return expected === undefined ? undefined : null; + } + var value = node.getAttribute(name); + if (value === '' + expected) { + return expected; + } + return value; + } +} + +/** + * Sets the value for a property on a node. + * + * @param {DOMElement} node + * @param {string} name + * @param {*} value + */ +function setValueForProperty(node, name, value, isCustomComponentTag) { + var propertyInfo = getPropertyInfo(name); + if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { + return; + } + if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { + value = null; + } + // If the prop isn't in the special list, treat it as a simple attribute. + if (isCustomComponentTag || propertyInfo === null) { + if (isAttributeNameSafe(name)) { + var _attributeName = name; + if (value === null) { + node.removeAttribute(_attributeName); + } else { + node.setAttribute(_attributeName, '' + value); + } + } + return; + } + var mustUseProperty = propertyInfo.mustUseProperty; + + if (mustUseProperty) { + var propertyName = propertyInfo.propertyName; + + if (value === null) { + var type = propertyInfo.type; + + node[propertyName] = type === BOOLEAN ? false : ''; + } else { + // Contrary to `setAttribute`, object properties are properly + // `toString`ed by IE8/9. + node[propertyName] = value; + } + return; + } + // The rest are treated as attributes with special cases. + var attributeName = propertyInfo.attributeName, + attributeNamespace = propertyInfo.attributeNamespace; + + if (value === null) { + node.removeAttribute(attributeName); + } else { + var _type = propertyInfo.type; + + var attributeValue = void 0; + if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { + attributeValue = ''; + } else { + // `setAttribute` with objects becomes only `[object]` in IE8/9, + // ('' + value) makes it output the correct toString()-value. + attributeValue = '' + value; + } + if (attributeNamespace) { + node.setAttributeNS(attributeNamespace, attributeName, attributeValue); + } else { + node.setAttribute(attributeName, attributeValue); + } + } +} + +var ReactControlledValuePropTypes = { + checkPropTypes: null +}; + +{ + var hasReadOnlyValue = { + button: true, + checkbox: true, + image: true, + hidden: true, + radio: true, + reset: true, + submit: true + }; + + var propTypes = { + value: function (props, propName, componentName) { + if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { + return null; + } + return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + }, + checked: function (props, propName, componentName) { + if (!props[propName] || props.onChange || props.readOnly || props.disabled) { + return null; + } + return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } + }; + + /** + * Provide a linked `value` attribute for controlled forms. You should not use + * this outside of the ReactDOM controlled form components. + */ + ReactControlledValuePropTypes.checkPropTypes = function (tagName, props, getStack) { + checkPropTypes(propTypes, props, 'prop', tagName, getStack); + }; +} + +// TODO: direct imports like some-package/src/* are bad. Fix me. +var getCurrentFiberOwnerName = ReactDebugCurrentFiber.getCurrentFiberOwnerName; +var getCurrentFiberStackAddendum = ReactDebugCurrentFiber.getCurrentFiberStackAddendum; + +var didWarnValueDefaultValue = false; +var didWarnCheckedDefaultChecked = false; +var didWarnControlledToUncontrolled = false; +var didWarnUncontrolledToControlled = false; + +function isControlled(props) { + var usesChecked = props.type === 'checkbox' || props.type === 'radio'; + return usesChecked ? props.checked != null : props.value != null; +} + +/** + * Implements an host component that allows setting these optional + * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. + * + * If `checked` or `value` are not supplied (or null/undefined), user actions + * that affect the checked state or value will trigger updates to the element. + * + * If they are supplied (and not null/undefined), the rendered element will not + * trigger updates to the element. Instead, the props must change in order for + * the rendered element to be updated. + * + * The rendered element will be initialized as unchecked (or `defaultChecked`) + * with an empty value (or `defaultValue`). + * + * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html + */ + +function getHostProps(element, props) { + var node = element; + var checked = props.checked; + + var hostProps = _assign({}, props, { + defaultChecked: undefined, + defaultValue: undefined, + value: undefined, + checked: checked != null ? checked : node._wrapperState.initialChecked + }); + + return hostProps; +} + +function initWrapperState(element, props) { + { + ReactControlledValuePropTypes.checkPropTypes('input', props, getCurrentFiberStackAddendum); + + if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { + warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerName() || 'A component', props.type); + didWarnCheckedDefaultChecked = true; + } + if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { + warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerName() || 'A component', props.type); + didWarnValueDefaultValue = true; + } + } + + var node = element; + var defaultValue = props.defaultValue == null ? '' : props.defaultValue; + + node._wrapperState = { + initialChecked: props.checked != null ? props.checked : props.defaultChecked, + initialValue: getSafeValue(props.value != null ? props.value : defaultValue), + controlled: isControlled(props) + }; +} + +function updateChecked(element, props) { + var node = element; + var checked = props.checked; + if (checked != null) { + setValueForProperty(node, 'checked', checked, false); + } +} + +function updateWrapper(element, props) { + var node = element; + { + var _controlled = isControlled(props); + + if (!node._wrapperState.controlled && _controlled && !didWarnUncontrolledToControlled) { + warning(false, 'A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s', props.type, getCurrentFiberStackAddendum()); + didWarnUncontrolledToControlled = true; + } + if (node._wrapperState.controlled && !_controlled && !didWarnControlledToUncontrolled) { + warning(false, 'A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s', props.type, getCurrentFiberStackAddendum()); + didWarnControlledToUncontrolled = true; + } + } + + updateChecked(element, props); + + var value = getSafeValue(props.value); + + if (value != null) { + if (props.type === 'number') { + if (value === 0 && node.value === '' || + // eslint-disable-next-line + node.value != value) { + node.value = '' + value; + } + } else if (node.value !== '' + value) { + node.value = '' + value; + } + } + + if (props.hasOwnProperty('value')) { + setDefaultValue(node, props.type, value); + } else if (props.hasOwnProperty('defaultValue')) { + setDefaultValue(node, props.type, getSafeValue(props.defaultValue)); + } + + if (props.checked == null && props.defaultChecked != null) { + node.defaultChecked = !!props.defaultChecked; + } +} + +function postMountWrapper(element, props, isHydrating) { + var node = element; + + if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) { + var _initialValue = '' + node._wrapperState.initialValue; + var currentValue = node.value; + + // Do not assign value if it is already set. This prevents user text input + // from being lost during SSR hydration. + if (!isHydrating) { + // Do not re-assign the value property if there is no change. This + // potentially avoids a DOM write and prevents Firefox (~60.0.1) from + // prematurely marking required inputs as invalid + if (_initialValue !== currentValue) { + node.value = _initialValue; + } + } + + // value must be assigned before defaultValue. This fixes an issue where the + // visually displayed value of date inputs disappears on mobile Safari and Chrome: + // https://github.com/facebook/react/issues/7233 + node.defaultValue = _initialValue; + } + + // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug + // this is needed to work around a chrome bug where setting defaultChecked + // will sometimes influence the value of checked (even after detachment). + // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 + // We need to temporarily unset name to avoid disrupting radio button groups. + var name = node.name; + if (name !== '') { + node.name = ''; + } + node.defaultChecked = !node.defaultChecked; + node.defaultChecked = !node.defaultChecked; + if (name !== '') { + node.name = name; + } +} + +function restoreControlledState(element, props) { + var node = element; + updateWrapper(node, props); + updateNamedCousins(node, props); +} + +function updateNamedCousins(rootNode, props) { + var name = props.name; + if (props.type === 'radio' && name != null) { + var queryRoot = rootNode; + + while (queryRoot.parentNode) { + queryRoot = queryRoot.parentNode; + } + + // If `rootNode.form` was non-null, then we could try `form.elements`, + // but that sometimes behaves strangely in IE8. We could also try using + // `form.getElementsByName`, but that will only return direct children + // and won't include inputs that use the HTML5 `form=` attribute. Since + // the input might not even be in a form. It might not even be in the + // document. Let's just use the local `querySelectorAll` to ensure we don't + // miss anything. + var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); + + for (var i = 0; i < group.length; i++) { + var otherNode = group[i]; + if (otherNode === rootNode || otherNode.form !== rootNode.form) { + continue; + } + // This will throw if radio buttons rendered by different copies of React + // and the same name are rendered into the same form (same as #1939). + // That's probably okay; we don't support it just as we don't support + // mixing React radio buttons with non-React ones. + var otherProps = getFiberCurrentPropsFromNode$1(otherNode); + !otherProps ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : void 0; + + // We need update the tracked value on the named cousin since the value + // was changed but the input saw no event or value set + updateValueIfChanged(otherNode); + + // If this is a controlled radio button group, forcing the input that + // was previously checked to update will cause it to be come re-checked + // as appropriate. + updateWrapper(otherNode, otherProps); + } + } +} + +// In Chrome, assigning defaultValue to certain input types triggers input validation. +// For number inputs, the display value loses trailing decimal points. For email inputs, +// Chrome raises "The specified value is not a valid email address". +// +// Here we check to see if the defaultValue has actually changed, avoiding these problems +// when the user is inputting text +// +// https://github.com/facebook/react/issues/7253 +function setDefaultValue(node, type, value) { + if ( + // Focused number inputs synchronize on blur. See ChangeEventPlugin.js + type !== 'number' || node.ownerDocument.activeElement !== node) { + if (value == null) { + node.defaultValue = '' + node._wrapperState.initialValue; + } else if (node.defaultValue !== '' + value) { + node.defaultValue = '' + value; + } + } +} + +function getSafeValue(value) { + switch (typeof value) { + case 'boolean': + case 'number': + case 'object': + case 'string': + case 'undefined': + return value; + default: + // function, symbol are assigned as empty strings + return ''; + } +} + +var eventTypes$1 = { + change: { + phasedRegistrationNames: { + bubbled: 'onChange', + captured: 'onChangeCapture' + }, + dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE] + } +}; + +function createAndAccumulateChangeEvent(inst, nativeEvent, target) { + var event = SyntheticEvent$1.getPooled(eventTypes$1.change, inst, nativeEvent, target); + event.type = 'change'; + // Flag this event loop as needing state restore. + enqueueStateRestore(target); + accumulateTwoPhaseDispatches(event); + return event; +} +/** + * For IE shims + */ +var activeElement = null; +var activeElementInst = null; + +/** + * SECTION: handle `change` event + */ +function shouldUseChangeEvent(elem) { + var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); + return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; +} + +function manualDispatchChangeEvent(nativeEvent) { + var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); + + // If change and propertychange bubbled, we'd just bind to it like all the + // other events and have it go through ReactBrowserEventEmitter. Since it + // doesn't, we manually listen for the events and so we have to enqueue and + // process the abstract event manually. + // + // Batching is necessary here in order to ensure that all event handlers run + // before the next rerender (including event handlers attached to ancestor + // elements instead of directly on the input). Without this, controlled + // components don't work properly in conjunction with event bubbling because + // the component is rerendered and the value reverted before all the event + // handlers can run. See https://github.com/facebook/react/issues/708. + batchedUpdates(runEventInBatch, event); +} + +function runEventInBatch(event) { + runEventsInBatch(event, false); +} + +function getInstIfValueChanged(targetInst) { + var targetNode = getNodeFromInstance$1(targetInst); + if (updateValueIfChanged(targetNode)) { + return targetInst; + } +} + +function getTargetInstForChangeEvent(topLevelType, targetInst) { + if (topLevelType === TOP_CHANGE) { + return targetInst; + } +} + +/** + * SECTION: handle `input` event + */ +var isInputEventSupported = false; +if (ExecutionEnvironment.canUseDOM) { + // IE9 claims to support the input event but fails to trigger it when + // deleting text, so we ignore its input events. + isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9); +} + +/** + * (For IE <=9) Starts tracking propertychange events on the passed-in element + * and override the value property so that we can distinguish user events from + * value changes in JS. + */ +function startWatchingForValueChange(target, targetInst) { + activeElement = target; + activeElementInst = targetInst; + activeElement.attachEvent('onpropertychange', handlePropertyChange); +} + +/** + * (For IE <=9) Removes the event listeners from the currently-tracked element, + * if any exists. + */ +function stopWatchingForValueChange() { + if (!activeElement) { + return; + } + activeElement.detachEvent('onpropertychange', handlePropertyChange); + activeElement = null; + activeElementInst = null; +} + +/** + * (For IE <=9) Handles a propertychange event, sending a `change` event if + * the value of the active element has changed. + */ +function handlePropertyChange(nativeEvent) { + if (nativeEvent.propertyName !== 'value') { + return; + } + if (getInstIfValueChanged(activeElementInst)) { + manualDispatchChangeEvent(nativeEvent); + } +} + +function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) { + if (topLevelType === TOP_FOCUS) { + // In IE9, propertychange fires for most input events but is buggy and + // doesn't fire when text is deleted, but conveniently, selectionchange + // appears to fire in all of the remaining cases so we catch those and + // forward the event if the value has changed + // In either case, we don't want to call the event handler if the value + // is changed from JS so we redefine a setter for `.value` that updates + // our activeElementValue variable, allowing us to ignore those changes + // + // stopWatching() should be a noop here but we call it just in case we + // missed a blur event somehow. + stopWatchingForValueChange(); + startWatchingForValueChange(target, targetInst); + } else if (topLevelType === TOP_BLUR) { + stopWatchingForValueChange(); + } +} + +// For IE8 and IE9. +function getTargetInstForInputEventPolyfill(topLevelType, targetInst) { + if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) { + // On the selectionchange event, the target is just document which isn't + // helpful for us so just check activeElement instead. + // + // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire + // propertychange on the first input event after setting `value` from a + // script and fires only keydown, keypress, keyup. Catching keyup usually + // gets it and catching keydown lets us fire an event for the first + // keystroke if user does a key repeat (it'll be a little delayed: right + // before the second keystroke). Other input methods (e.g., paste) seem to + // fire selectionchange normally. + return getInstIfValueChanged(activeElementInst); + } +} + +/** + * SECTION: handle `click` event + */ +function shouldUseClickEvent(elem) { + // Use the `click` event to detect changes to checkbox and radio inputs. + // This approach works across all browsers, whereas `change` does not fire + // until `blur` in IE8. + var nodeName = elem.nodeName; + return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); +} + +function getTargetInstForClickEvent(topLevelType, targetInst) { + if (topLevelType === TOP_CLICK) { + return getInstIfValueChanged(targetInst); + } +} + +function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) { + if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) { + return getInstIfValueChanged(targetInst); + } +} + +function handleControlledInputBlur(node) { + var state = node._wrapperState; + + if (!state || !state.controlled || node.type !== 'number') { + return; + } + + // If controlled, assign the value attribute to the current value on blur + setDefaultValue(node, 'number', node.value); +} + +/** + * This plugin creates an `onChange` event that normalizes change events + * across form elements. This event fires at a time when it's possible to + * change the element's value without seeing a flicker. + * + * Supported elements are: + * - input (see `isTextInputElement`) + * - textarea + * - select + */ +var ChangeEventPlugin = { + eventTypes: eventTypes$1, + + _isInputEventSupported: isInputEventSupported, + + extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window; + + var getTargetInstFunc = void 0, + handleEventFunc = void 0; + if (shouldUseChangeEvent(targetNode)) { + getTargetInstFunc = getTargetInstForChangeEvent; + } else if (isTextInputElement(targetNode)) { + if (isInputEventSupported) { + getTargetInstFunc = getTargetInstForInputOrChangeEvent; + } else { + getTargetInstFunc = getTargetInstForInputEventPolyfill; + handleEventFunc = handleEventsForInputEventPolyfill; + } + } else if (shouldUseClickEvent(targetNode)) { + getTargetInstFunc = getTargetInstForClickEvent; + } + + if (getTargetInstFunc) { + var inst = getTargetInstFunc(topLevelType, targetInst); + if (inst) { + var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget); + return event; + } + } + + if (handleEventFunc) { + handleEventFunc(topLevelType, targetNode, targetInst); + } + + // When blurring, set the value attribute for number inputs + if (topLevelType === TOP_BLUR) { + handleControlledInputBlur(targetNode); + } + } +}; + +/** + * Module that is injectable into `EventPluginHub`, that specifies a + * deterministic ordering of `EventPlugin`s. A convenient way to reason about + * plugins, without having to package every one of them. This is better than + * having plugins be ordered in the same order that they are injected because + * that ordering would be influenced by the packaging order. + * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that + * preventing default on events is convenient in `SimpleEventPlugin` handlers. + */ +var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'TapEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin']; + +var SyntheticUIEvent = SyntheticEvent$1.extend({ + view: null, + detail: null +}); + +/** + * Translation from modifier key to the associated property in the event. + * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers + */ + +var modifierKeyToProp = { + Alt: 'altKey', + Control: 'ctrlKey', + Meta: 'metaKey', + Shift: 'shiftKey' +}; + +// IE8 does not implement getModifierState so we simply map it to the only +// modifier keys exposed by the event itself, does not support Lock-keys. +// Currently, all major browsers except Chrome seems to support Lock-keys. +function modifierStateGetter(keyArg) { + var syntheticEvent = this; + var nativeEvent = syntheticEvent.nativeEvent; + if (nativeEvent.getModifierState) { + return nativeEvent.getModifierState(keyArg); + } + var keyProp = modifierKeyToProp[keyArg]; + return keyProp ? !!nativeEvent[keyProp] : false; +} + +function getEventModifierState(nativeEvent) { + return modifierStateGetter; +} + +/** + * @interface MouseEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var SyntheticMouseEvent = SyntheticUIEvent.extend({ + screenX: null, + screenY: null, + clientX: null, + clientY: null, + pageX: null, + pageY: null, + ctrlKey: null, + shiftKey: null, + altKey: null, + metaKey: null, + getModifierState: getEventModifierState, + button: null, + buttons: null, + relatedTarget: function (event) { + return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); + } +}); + +/** + * @interface PointerEvent + * @see http://www.w3.org/TR/pointerevents/ + */ +var SyntheticPointerEvent = SyntheticMouseEvent.extend({ + pointerId: null, + width: null, + height: null, + pressure: null, + tiltX: null, + tiltY: null, + pointerType: null, + isPrimary: null +}); + +var eventTypes$2 = { + mouseEnter: { + registrationName: 'onMouseEnter', + dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER] + }, + mouseLeave: { + registrationName: 'onMouseLeave', + dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER] + }, + pointerEnter: { + registrationName: 'onPointerEnter', + dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER] + }, + pointerLeave: { + registrationName: 'onPointerLeave', + dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER] + } +}; + +var EnterLeaveEventPlugin = { + eventTypes: eventTypes$2, + + /** + * For almost every interaction we care about, there will be both a top-level + * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that + * we do not extract duplicate events. However, moving the mouse into the + * browser from outside will not fire a `mouseout` event. In this case, we use + * the `mouseover` top-level event. + */ + extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER; + var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT; + + if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { + return null; + } + + if (!isOutEvent && !isOverEvent) { + // Must not be a mouse or pointer in or out - ignoring. + return null; + } + + var win = void 0; + if (nativeEventTarget.window === nativeEventTarget) { + // `nativeEventTarget` is probably a window object. + win = nativeEventTarget; + } else { + // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. + var doc = nativeEventTarget.ownerDocument; + if (doc) { + win = doc.defaultView || doc.parentWindow; + } else { + win = window; + } + } + + var from = void 0; + var to = void 0; + if (isOutEvent) { + from = targetInst; + var related = nativeEvent.relatedTarget || nativeEvent.toElement; + to = related ? getClosestInstanceFromNode(related) : null; + } else { + // Moving to a node from outside the window. + from = null; + to = targetInst; + } + + if (from === to) { + // Nothing pertains to our managed components. + return null; + } + + var eventInterface = void 0, + leaveEventType = void 0, + enterEventType = void 0, + eventTypePrefix = void 0; + + if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) { + eventInterface = SyntheticMouseEvent; + leaveEventType = eventTypes$2.mouseLeave; + enterEventType = eventTypes$2.mouseEnter; + eventTypePrefix = 'mouse'; + } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) { + eventInterface = SyntheticPointerEvent; + leaveEventType = eventTypes$2.pointerLeave; + enterEventType = eventTypes$2.pointerEnter; + eventTypePrefix = 'pointer'; + } + + var fromNode = from == null ? win : getNodeFromInstance$1(from); + var toNode = to == null ? win : getNodeFromInstance$1(to); + + var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget); + leave.type = eventTypePrefix + 'leave'; + leave.target = fromNode; + leave.relatedTarget = toNode; + + var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget); + enter.type = eventTypePrefix + 'enter'; + enter.target = toNode; + enter.relatedTarget = fromNode; + + accumulateEnterLeaveDispatches(leave, enter, from, to); + + return [leave, enter]; + } +}; + +/** + * `ReactInstanceMap` maintains a mapping from a public facing stateful + * instance (key) and the internal representation (value). This allows public + * methods to accept the user facing instance as an argument and map them back + * to internal methods. + * + * Note that this module is currently shared and assumed to be stateless. + * If this becomes an actual Map, that will break. + */ + +/** + * This API should be called `delete` but we'd have to make sure to always + * transform these to strings for IE support. When this transform is fully + * supported we can rename it. + */ + + +function get(key) { + return key._reactInternalFiber; +} + +function has(key) { + return key._reactInternalFiber !== undefined; +} + +function set(key, value) { + key._reactInternalFiber = value; +} + +// Don't change these two values. They're used by React Dev Tools. +var NoEffect = /* */0; +var PerformedWork = /* */1; + +// You can change the rest (and add more). +var Placement = /* */2; +var Update = /* */4; +var PlacementAndUpdate = /* */6; +var Deletion = /* */8; +var ContentReset = /* */16; +var Callback = /* */32; +var DidCapture = /* */64; +var Ref = /* */128; +var Snapshot = /* */256; + +// Union of all host effects +var HostEffectMask = /* */511; + +var Incomplete = /* */512; +var ShouldCapture = /* */1024; + +var MOUNTING = 1; +var MOUNTED = 2; +var UNMOUNTED = 3; + +function isFiberMountedImpl(fiber) { + var node = fiber; + if (!fiber.alternate) { + // If there is no alternate, this might be a new tree that isn't inserted + // yet. If it is, then it will have a pending insertion effect on it. + if ((node.effectTag & Placement) !== NoEffect) { + return MOUNTING; + } + while (node.return) { + node = node.return; + if ((node.effectTag & Placement) !== NoEffect) { + return MOUNTING; + } + } + } else { + while (node.return) { + node = node.return; + } + } + if (node.tag === HostRoot) { + // TODO: Check if this was a nested HostRoot when used with + // renderContainerIntoSubtree. + return MOUNTED; + } + // If we didn't hit the root, that means that we're in an disconnected tree + // that has been unmounted. + return UNMOUNTED; +} + +function isFiberMounted(fiber) { + return isFiberMountedImpl(fiber) === MOUNTED; +} + +function isMounted(component) { + { + var owner = ReactCurrentOwner.current; + if (owner !== null && owner.tag === ClassComponent) { + var ownerFiber = owner; + var instance = ownerFiber.stateNode; + !instance._warnedAboutRefsInRender ? warning(false, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber) || 'A component') : void 0; + instance._warnedAboutRefsInRender = true; + } + } + + var fiber = get(component); + if (!fiber) { + return false; + } + return isFiberMountedImpl(fiber) === MOUNTED; +} + +function assertIsMounted(fiber) { + !(isFiberMountedImpl(fiber) === MOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0; +} + +function findCurrentFiberUsingSlowPath(fiber) { + var alternate = fiber.alternate; + if (!alternate) { + // If there is no alternate, then we only need to check if it is mounted. + var state = isFiberMountedImpl(fiber); + !(state !== UNMOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0; + if (state === MOUNTING) { + return null; + } + return fiber; + } + // If we have two possible branches, we'll walk backwards up to the root + // to see what path the root points to. On the way we may hit one of the + // special cases and we'll deal with them. + var a = fiber; + var b = alternate; + while (true) { + var parentA = a.return; + var parentB = parentA ? parentA.alternate : null; + if (!parentA || !parentB) { + // We're at the root. + break; + } + + // If both copies of the parent fiber point to the same child, we can + // assume that the child is current. This happens when we bailout on low + // priority: the bailed out fiber's child reuses the current child. + if (parentA.child === parentB.child) { + var child = parentA.child; + while (child) { + if (child === a) { + // We've determined that A is the current branch. + assertIsMounted(parentA); + return fiber; + } + if (child === b) { + // We've determined that B is the current branch. + assertIsMounted(parentA); + return alternate; + } + child = child.sibling; + } + // We should never have an alternate for any mounting node. So the only + // way this could possibly happen is if this was unmounted, if at all. + invariant(false, 'Unable to find node on an unmounted component.'); + } + + if (a.return !== b.return) { + // The return pointer of A and the return pointer of B point to different + // fibers. We assume that return pointers never criss-cross, so A must + // belong to the child set of A.return, and B must belong to the child + // set of B.return. + a = parentA; + b = parentB; + } else { + // The return pointers point to the same fiber. We'll have to use the + // default, slow path: scan the child sets of each parent alternate to see + // which child belongs to which set. + // + // Search parent A's child set + var didFindChild = false; + var _child = parentA.child; + while (_child) { + if (_child === a) { + didFindChild = true; + a = parentA; + b = parentB; + break; + } + if (_child === b) { + didFindChild = true; + b = parentA; + a = parentB; + break; + } + _child = _child.sibling; + } + if (!didFindChild) { + // Search parent B's child set + _child = parentB.child; + while (_child) { + if (_child === a) { + didFindChild = true; + a = parentB; + b = parentA; + break; + } + if (_child === b) { + didFindChild = true; + b = parentB; + a = parentA; + break; + } + _child = _child.sibling; + } + !didFindChild ? invariant(false, 'Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.') : void 0; + } + } + + !(a.alternate === b) ? invariant(false, 'Return fibers should always be each others\' alternates. This error is likely caused by a bug in React. Please file an issue.') : void 0; + } + // If the root is not a host container, we're in a disconnected tree. I.e. + // unmounted. + !(a.tag === HostRoot) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0; + if (a.stateNode.current === a) { + // We've determined that A is the current branch. + return fiber; + } + // Otherwise B has to be current branch. + return alternate; +} + +function findCurrentHostFiber(parent) { + var currentParent = findCurrentFiberUsingSlowPath(parent); + if (!currentParent) { + return null; + } + + // Next we'll drill down this component to find the first HostComponent/Text. + var node = currentParent; + while (true) { + if (node.tag === HostComponent || node.tag === HostText) { + return node; + } else if (node.child) { + node.child.return = node; + node = node.child; + continue; + } + if (node === currentParent) { + return null; + } + while (!node.sibling) { + if (!node.return || node.return === currentParent) { + return null; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + // Flow needs the return null here, but ESLint complains about it. + // eslint-disable-next-line no-unreachable + return null; +} + +function findCurrentHostFiberWithNoPortals(parent) { + var currentParent = findCurrentFiberUsingSlowPath(parent); + if (!currentParent) { + return null; + } + + // Next we'll drill down this component to find the first HostComponent/Text. + var node = currentParent; + while (true) { + if (node.tag === HostComponent || node.tag === HostText) { + return node; + } else if (node.child && node.tag !== HostPortal) { + node.child.return = node; + node = node.child; + continue; + } + if (node === currentParent) { + return null; + } + while (!node.sibling) { + if (!node.return || node.return === currentParent) { + return null; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + // Flow needs the return null here, but ESLint complains about it. + // eslint-disable-next-line no-unreachable + return null; +} + +function addEventBubbleListener(element, eventType, listener) { + element.addEventListener(eventType, listener, false); +} + +function addEventCaptureListener(element, eventType, listener) { + element.addEventListener(eventType, listener, true); +} + +/** + * @interface Event + * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface + * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent + */ +var SyntheticAnimationEvent = SyntheticEvent$1.extend({ + animationName: null, + elapsedTime: null, + pseudoElement: null +}); + +/** + * @interface Event + * @see http://www.w3.org/TR/clipboard-apis/ + */ +var SyntheticClipboardEvent = SyntheticEvent$1.extend({ + clipboardData: function (event) { + return 'clipboardData' in event ? event.clipboardData : window.clipboardData; + } +}); + +/** + * @interface FocusEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var SyntheticFocusEvent = SyntheticUIEvent.extend({ + relatedTarget: null +}); + +/** + * `charCode` represents the actual "character code" and is safe to use with + * `String.fromCharCode`. As such, only keys that correspond to printable + * characters produce a valid `charCode`, the only exception to this is Enter. + * The Tab-key is considered non-printable and does not have a `charCode`, + * presumably because it does not produce a tab-character in browsers. + * + * @param {object} nativeEvent Native browser event. + * @return {number} Normalized `charCode` property. + */ +function getEventCharCode(nativeEvent) { + var charCode = void 0; + var keyCode = nativeEvent.keyCode; + + if ('charCode' in nativeEvent) { + charCode = nativeEvent.charCode; + + // FF does not set `charCode` for the Enter-key, check against `keyCode`. + if (charCode === 0 && keyCode === 13) { + charCode = 13; + } + } else { + // IE8 does not implement `charCode`, but `keyCode` has the correct value. + charCode = keyCode; + } + + // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux) + // report Enter as charCode 10 when ctrl is pressed. + if (charCode === 10) { + charCode = 13; + } + + // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. + // Must not discard the (non-)printable Enter-key. + if (charCode >= 32 || charCode === 13) { + return charCode; + } + + return 0; +} + +/** + * Normalization of deprecated HTML5 `key` values + * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names + */ +var normalizeKey = { + Esc: 'Escape', + Spacebar: ' ', + Left: 'ArrowLeft', + Up: 'ArrowUp', + Right: 'ArrowRight', + Down: 'ArrowDown', + Del: 'Delete', + Win: 'OS', + Menu: 'ContextMenu', + Apps: 'ContextMenu', + Scroll: 'ScrollLock', + MozPrintableKey: 'Unidentified' +}; + +/** + * Translation from legacy `keyCode` to HTML5 `key` + * Only special keys supported, all others depend on keyboard layout or browser + * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names + */ +var translateToKey = { + '8': 'Backspace', + '9': 'Tab', + '12': 'Clear', + '13': 'Enter', + '16': 'Shift', + '17': 'Control', + '18': 'Alt', + '19': 'Pause', + '20': 'CapsLock', + '27': 'Escape', + '32': ' ', + '33': 'PageUp', + '34': 'PageDown', + '35': 'End', + '36': 'Home', + '37': 'ArrowLeft', + '38': 'ArrowUp', + '39': 'ArrowRight', + '40': 'ArrowDown', + '45': 'Insert', + '46': 'Delete', + '112': 'F1', + '113': 'F2', + '114': 'F3', + '115': 'F4', + '116': 'F5', + '117': 'F6', + '118': 'F7', + '119': 'F8', + '120': 'F9', + '121': 'F10', + '122': 'F11', + '123': 'F12', + '144': 'NumLock', + '145': 'ScrollLock', + '224': 'Meta' +}; + +/** + * @param {object} nativeEvent Native browser event. + * @return {string} Normalized `key` property. + */ +function getEventKey(nativeEvent) { + if (nativeEvent.key) { + // Normalize inconsistent values reported by browsers due to + // implementations of a working draft specification. + + // FireFox implements `key` but returns `MozPrintableKey` for all + // printable characters (normalized to `Unidentified`), ignore it. + var key = normalizeKey[nativeEvent.key] || nativeEvent.key; + if (key !== 'Unidentified') { + return key; + } + } + + // Browser does not implement `key`, polyfill as much of it as we can. + if (nativeEvent.type === 'keypress') { + var charCode = getEventCharCode(nativeEvent); + + // The enter-key is technically both printable and non-printable and can + // thus be captured by `keypress`, no other non-printable key should. + return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); + } + if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { + // While user keyboard layout determines the actual meaning of each + // `keyCode` value, almost all function keys have a universal value. + return translateToKey[nativeEvent.keyCode] || 'Unidentified'; + } + return ''; +} + +/** + * @interface KeyboardEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var SyntheticKeyboardEvent = SyntheticUIEvent.extend({ + key: getEventKey, + location: null, + ctrlKey: null, + shiftKey: null, + altKey: null, + metaKey: null, + repeat: null, + locale: null, + getModifierState: getEventModifierState, + // Legacy Interface + charCode: function (event) { + // `charCode` is the result of a KeyPress event and represents the value of + // the actual printable character. + + // KeyPress is deprecated, but its replacement is not yet final and not + // implemented in any major browser. Only KeyPress has charCode. + if (event.type === 'keypress') { + return getEventCharCode(event); + } + return 0; + }, + keyCode: function (event) { + // `keyCode` is the result of a KeyDown/Up event and represents the value of + // physical keyboard key. + + // The actual meaning of the value depends on the users' keyboard layout + // which cannot be detected. Assuming that it is a US keyboard layout + // provides a surprisingly accurate mapping for US and European users. + // Due to this, it is left to the user to implement at this time. + if (event.type === 'keydown' || event.type === 'keyup') { + return event.keyCode; + } + return 0; + }, + which: function (event) { + // `which` is an alias for either `keyCode` or `charCode` depending on the + // type of the event. + if (event.type === 'keypress') { + return getEventCharCode(event); + } + if (event.type === 'keydown' || event.type === 'keyup') { + return event.keyCode; + } + return 0; + } +}); + +/** + * @interface DragEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var SyntheticDragEvent = SyntheticMouseEvent.extend({ + dataTransfer: null +}); + +/** + * @interface TouchEvent + * @see http://www.w3.org/TR/touch-events/ + */ +var SyntheticTouchEvent = SyntheticUIEvent.extend({ + touches: null, + targetTouches: null, + changedTouches: null, + altKey: null, + metaKey: null, + ctrlKey: null, + shiftKey: null, + getModifierState: getEventModifierState +}); + +/** + * @interface Event + * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- + * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent + */ +var SyntheticTransitionEvent = SyntheticEvent$1.extend({ + propertyName: null, + elapsedTime: null, + pseudoElement: null +}); + +/** + * @interface WheelEvent + * @see http://www.w3.org/TR/DOM-Level-3-Events/ + */ +var SyntheticWheelEvent = SyntheticMouseEvent.extend({ + deltaX: function (event) { + return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). + 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; + }, + deltaY: function (event) { + return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). + 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). + 'wheelDelta' in event ? -event.wheelDelta : 0; + }, + + deltaZ: null, + + // Browsers without "deltaMode" is reporting in raw wheel delta where one + // notch on the scroll is always +/- 120, roughly equivalent to pixels. + // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or + // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. + deltaMode: null +}); + +/** + * Turns + * ['abort', ...] + * into + * eventTypes = { + * 'abort': { + * phasedRegistrationNames: { + * bubbled: 'onAbort', + * captured: 'onAbortCapture', + * }, + * dependencies: [TOP_ABORT], + * }, + * ... + * }; + * topLevelEventsToDispatchConfig = new Map([ + * [TOP_ABORT, { sameConfig }], + * ]); + */ + +var interactiveEventTypeNames = [[TOP_BLUR, 'blur'], [TOP_CANCEL, 'cancel'], [TOP_CLICK, 'click'], [TOP_CLOSE, 'close'], [TOP_CONTEXT_MENU, 'contextMenu'], [TOP_COPY, 'copy'], [TOP_CUT, 'cut'], [TOP_DOUBLE_CLICK, 'doubleClick'], [TOP_DRAG_END, 'dragEnd'], [TOP_DRAG_START, 'dragStart'], [TOP_DROP, 'drop'], [TOP_FOCUS, 'focus'], [TOP_INPUT, 'input'], [TOP_INVALID, 'invalid'], [TOP_KEY_DOWN, 'keyDown'], [TOP_KEY_PRESS, 'keyPress'], [TOP_KEY_UP, 'keyUp'], [TOP_MOUSE_DOWN, 'mouseDown'], [TOP_MOUSE_UP, 'mouseUp'], [TOP_PASTE, 'paste'], [TOP_PAUSE, 'pause'], [TOP_PLAY, 'play'], [TOP_POINTER_CANCEL, 'pointerCancel'], [TOP_POINTER_DOWN, 'pointerDown'], [TOP_POINTER_UP, 'pointerUp'], [TOP_RATE_CHANGE, 'rateChange'], [TOP_RESET, 'reset'], [TOP_SEEKED, 'seeked'], [TOP_SUBMIT, 'submit'], [TOP_TOUCH_CANCEL, 'touchCancel'], [TOP_TOUCH_END, 'touchEnd'], [TOP_TOUCH_START, 'touchStart'], [TOP_VOLUME_CHANGE, 'volumeChange']]; +var nonInteractiveEventTypeNames = [[TOP_ABORT, 'abort'], [TOP_ANIMATION_END, 'animationEnd'], [TOP_ANIMATION_ITERATION, 'animationIteration'], [TOP_ANIMATION_START, 'animationStart'], [TOP_CAN_PLAY, 'canPlay'], [TOP_CAN_PLAY_THROUGH, 'canPlayThrough'], [TOP_DRAG, 'drag'], [TOP_DRAG_ENTER, 'dragEnter'], [TOP_DRAG_EXIT, 'dragExit'], [TOP_DRAG_LEAVE, 'dragLeave'], [TOP_DRAG_OVER, 'dragOver'], [TOP_DURATION_CHANGE, 'durationChange'], [TOP_EMPTIED, 'emptied'], [TOP_ENCRYPTED, 'encrypted'], [TOP_ENDED, 'ended'], [TOP_ERROR, 'error'], [TOP_GOT_POINTER_CAPTURE, 'gotPointerCapture'], [TOP_LOAD, 'load'], [TOP_LOADED_DATA, 'loadedData'], [TOP_LOADED_METADATA, 'loadedMetadata'], [TOP_LOAD_START, 'loadStart'], [TOP_LOST_POINTER_CAPTURE, 'lostPointerCapture'], [TOP_MOUSE_MOVE, 'mouseMove'], [TOP_MOUSE_OUT, 'mouseOut'], [TOP_MOUSE_OVER, 'mouseOver'], [TOP_PLAYING, 'playing'], [TOP_POINTER_MOVE, 'pointerMove'], [TOP_POINTER_OUT, 'pointerOut'], [TOP_POINTER_OVER, 'pointerOver'], [TOP_PROGRESS, 'progress'], [TOP_SCROLL, 'scroll'], [TOP_SEEKING, 'seeking'], [TOP_STALLED, 'stalled'], [TOP_SUSPEND, 'suspend'], [TOP_TIME_UPDATE, 'timeUpdate'], [TOP_TOGGLE, 'toggle'], [TOP_TOUCH_MOVE, 'touchMove'], [TOP_TRANSITION_END, 'transitionEnd'], [TOP_WAITING, 'waiting'], [TOP_WHEEL, 'wheel']]; + +var eventTypes$4 = {}; +var topLevelEventsToDispatchConfig = {}; + +function addEventTypeNameToConfig(_ref, isInteractive) { + var topEvent = _ref[0], + event = _ref[1]; + + var capitalizedEvent = event[0].toUpperCase() + event.slice(1); + var onEvent = 'on' + capitalizedEvent; + + var type = { + phasedRegistrationNames: { + bubbled: onEvent, + captured: onEvent + 'Capture' + }, + dependencies: [topEvent], + isInteractive: isInteractive + }; + eventTypes$4[event] = type; + topLevelEventsToDispatchConfig[topEvent] = type; +} + +interactiveEventTypeNames.forEach(function (eventTuple) { + addEventTypeNameToConfig(eventTuple, true); +}); +nonInteractiveEventTypeNames.forEach(function (eventTuple) { + addEventTypeNameToConfig(eventTuple, false); +}); + +// Only used in DEV for exhaustiveness validation. +var knownHTMLTopLevelTypes = [TOP_ABORT, TOP_CANCEL, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_CLOSE, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_INPUT, TOP_INVALID, TOP_LOAD, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_RESET, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUBMIT, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_TOGGLE, TOP_VOLUME_CHANGE, TOP_WAITING]; + +var SimpleEventPlugin = { + eventTypes: eventTypes$4, + + isInteractiveTopLevelEventType: function (topLevelType) { + var config = topLevelEventsToDispatchConfig[topLevelType]; + return config !== undefined && config.isInteractive === true; + }, + + + extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; + if (!dispatchConfig) { + return null; + } + var EventConstructor = void 0; + switch (topLevelType) { + case TOP_KEY_PRESS: + // Firefox creates a keypress event for function keys too. This removes + // the unwanted keypress events. Enter is however both printable and + // non-printable. One would expect Tab to be as well (but it isn't). + if (getEventCharCode(nativeEvent) === 0) { + return null; + } + /* falls through */ + case TOP_KEY_DOWN: + case TOP_KEY_UP: + EventConstructor = SyntheticKeyboardEvent; + break; + case TOP_BLUR: + case TOP_FOCUS: + EventConstructor = SyntheticFocusEvent; + break; + case TOP_CLICK: + // Firefox creates a click event on right mouse clicks. This removes the + // unwanted click events. + if (nativeEvent.button === 2) { + return null; + } + /* falls through */ + case TOP_DOUBLE_CLICK: + case TOP_MOUSE_DOWN: + case TOP_MOUSE_MOVE: + case TOP_MOUSE_UP: + // TODO: Disabled elements should not respond to mouse events + /* falls through */ + case TOP_MOUSE_OUT: + case TOP_MOUSE_OVER: + case TOP_CONTEXT_MENU: + EventConstructor = SyntheticMouseEvent; + break; + case TOP_DRAG: + case TOP_DRAG_END: + case TOP_DRAG_ENTER: + case TOP_DRAG_EXIT: + case TOP_DRAG_LEAVE: + case TOP_DRAG_OVER: + case TOP_DRAG_START: + case TOP_DROP: + EventConstructor = SyntheticDragEvent; + break; + case TOP_TOUCH_CANCEL: + case TOP_TOUCH_END: + case TOP_TOUCH_MOVE: + case TOP_TOUCH_START: + EventConstructor = SyntheticTouchEvent; + break; + case TOP_ANIMATION_END: + case TOP_ANIMATION_ITERATION: + case TOP_ANIMATION_START: + EventConstructor = SyntheticAnimationEvent; + break; + case TOP_TRANSITION_END: + EventConstructor = SyntheticTransitionEvent; + break; + case TOP_SCROLL: + EventConstructor = SyntheticUIEvent; + break; + case TOP_WHEEL: + EventConstructor = SyntheticWheelEvent; + break; + case TOP_COPY: + case TOP_CUT: + case TOP_PASTE: + EventConstructor = SyntheticClipboardEvent; + break; + case TOP_GOT_POINTER_CAPTURE: + case TOP_LOST_POINTER_CAPTURE: + case TOP_POINTER_CANCEL: + case TOP_POINTER_DOWN: + case TOP_POINTER_MOVE: + case TOP_POINTER_OUT: + case TOP_POINTER_OVER: + case TOP_POINTER_UP: + EventConstructor = SyntheticPointerEvent; + break; + default: + { + if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) { + warning(false, 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType); + } + } + // HTML Events + // @see http://www.w3.org/TR/html5/index.html#events-0 + EventConstructor = SyntheticEvent$1; + break; + } + var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); + accumulateTwoPhaseDispatches(event); + return event; + } +}; + +var isInteractiveTopLevelEventType = SimpleEventPlugin.isInteractiveTopLevelEventType; + + +var CALLBACK_BOOKKEEPING_POOL_SIZE = 10; +var callbackBookkeepingPool = []; + +/** + * Find the deepest React component completely containing the root of the + * passed-in instance (for use when entire React trees are nested within each + * other). If React trees are not nested, returns null. + */ +function findRootContainerNode(inst) { + // TODO: It may be a good idea to cache this to prevent unnecessary DOM + // traversal, but caching is difficult to do correctly without using a + // mutation observer to listen for all DOM changes. + while (inst.return) { + inst = inst.return; + } + if (inst.tag !== HostRoot) { + // This can happen if we're in a detached tree. + return null; + } + return inst.stateNode.containerInfo; +} + +// Used to store ancestor hierarchy in top level callback +function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst) { + if (callbackBookkeepingPool.length) { + var instance = callbackBookkeepingPool.pop(); + instance.topLevelType = topLevelType; + instance.nativeEvent = nativeEvent; + instance.targetInst = targetInst; + return instance; + } + return { + topLevelType: topLevelType, + nativeEvent: nativeEvent, + targetInst: targetInst, + ancestors: [] + }; +} + +function releaseTopLevelCallbackBookKeeping(instance) { + instance.topLevelType = null; + instance.nativeEvent = null; + instance.targetInst = null; + instance.ancestors.length = 0; + if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) { + callbackBookkeepingPool.push(instance); + } +} + +function handleTopLevel(bookKeeping) { + var targetInst = bookKeeping.targetInst; + + // Loop through the hierarchy, in case there's any nested components. + // It's important that we build the array of ancestors before calling any + // event handlers, because event handlers can modify the DOM, leading to + // inconsistencies with ReactMount's node cache. See #1105. + var ancestor = targetInst; + do { + if (!ancestor) { + bookKeeping.ancestors.push(ancestor); + break; + } + var root = findRootContainerNode(ancestor); + if (!root) { + break; + } + bookKeeping.ancestors.push(ancestor); + ancestor = getClosestInstanceFromNode(root); + } while (ancestor); + + for (var i = 0; i < bookKeeping.ancestors.length; i++) { + targetInst = bookKeeping.ancestors[i]; + runExtractedEventsInBatch(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); + } +} + +// TODO: can we stop exporting these? +var _enabled = true; + +function setEnabled(enabled) { + _enabled = !!enabled; +} + +function isEnabled() { + return _enabled; +} + +/** + * Traps top-level events by using event bubbling. + * + * @param {number} topLevelType Number from `TopLevelEventTypes`. + * @param {object} element Element on which to attach listener. + * @return {?object} An object with a remove function which will forcefully + * remove the listener. + * @internal + */ +function trapBubbledEvent(topLevelType, element) { + if (!element) { + return null; + } + var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent; + + addEventBubbleListener(element, getRawEventName(topLevelType), + // Check if interactive and wrap in interactiveUpdates + dispatch.bind(null, topLevelType)); +} + +/** + * Traps a top-level event by using event capturing. + * + * @param {number} topLevelType Number from `TopLevelEventTypes`. + * @param {object} element Element on which to attach listener. + * @return {?object} An object with a remove function which will forcefully + * remove the listener. + * @internal + */ +function trapCapturedEvent(topLevelType, element) { + if (!element) { + return null; + } + var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent; + + addEventCaptureListener(element, getRawEventName(topLevelType), + // Check if interactive and wrap in interactiveUpdates + dispatch.bind(null, topLevelType)); +} + +function dispatchInteractiveEvent(topLevelType, nativeEvent) { + interactiveUpdates(dispatchEvent, topLevelType, nativeEvent); +} + +function dispatchEvent(topLevelType, nativeEvent) { + if (!_enabled) { + return; + } + + var nativeEventTarget = getEventTarget(nativeEvent); + var targetInst = getClosestInstanceFromNode(nativeEventTarget); + if (targetInst !== null && typeof targetInst.tag === 'number' && !isFiberMounted(targetInst)) { + // If we get an event (ex: img onload) before committing that + // component's mount, ignore it for now (that is, treat it as if it was an + // event on a non-React tree). We might also consider queueing events and + // dispatching them after the mount. + targetInst = null; + } + + var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst); + + try { + // Event queue being processed in the same cycle allows + // `preventDefault`. + batchedUpdates(handleTopLevel, bookKeeping); + } finally { + releaseTopLevelCallbackBookKeeping(bookKeeping); + } +} + +var ReactDOMEventListener = Object.freeze({ + get _enabled () { return _enabled; }, + setEnabled: setEnabled, + isEnabled: isEnabled, + trapBubbledEvent: trapBubbledEvent, + trapCapturedEvent: trapCapturedEvent, + dispatchEvent: dispatchEvent +}); + +/** + * Summary of `ReactBrowserEventEmitter` event handling: + * + * - Top-level delegation is used to trap most native browser events. This + * may only occur in the main thread and is the responsibility of + * ReactDOMEventListener, which is injected and can therefore support + * pluggable event sources. This is the only work that occurs in the main + * thread. + * + * - We normalize and de-duplicate events to account for browser quirks. This + * may be done in the worker thread. + * + * - Forward these native events (with the associated top-level type used to + * trap it) to `EventPluginHub`, which in turn will ask plugins if they want + * to extract any synthetic events. + * + * - The `EventPluginHub` will then process each event by annotating them with + * "dispatches", a sequence of listeners and IDs that care about that event. + * + * - The `EventPluginHub` then dispatches the events. + * + * Overview of React and the event system: + * + * +------------+ . + * | DOM | . + * +------------+ . + * | . + * v . + * +------------+ . + * | ReactEvent | . + * | Listener | . + * +------------+ . +-----------+ + * | . +--------+|SimpleEvent| + * | . | |Plugin | + * +-----|------+ . v +-----------+ + * | | | . +--------------+ +------------+ + * | +-----------.--->|EventPluginHub| | Event | + * | | . | | +-----------+ | Propagators| + * | ReactEvent | . | | |TapEvent | |------------| + * | Emitter | . | |<---+|Plugin | |other plugin| + * | | . | | +-----------+ | utilities | + * | +-----------.--->| | +------------+ + * | | | . +--------------+ + * +-----|------+ . ^ +-----------+ + * | . | |Enter/Leave| + * + . +-------+|Plugin | + * +-------------+ . +-----------+ + * | application | . + * |-------------| . + * | | . + * | | . + * +-------------+ . + * . + * React Core . General Purpose Event Plugin System + */ + +var alreadyListeningTo = {}; +var reactTopListenersCounter = 0; + +/** + * To ensure no conflicts with other potential React instances on the page + */ +var topListenersIDKey = '_reactListenersID' + ('' + Math.random()).slice(2); + +function getListeningForDocument(mountAt) { + // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` + // directly. + if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { + mountAt[topListenersIDKey] = reactTopListenersCounter++; + alreadyListeningTo[mountAt[topListenersIDKey]] = {}; + } + return alreadyListeningTo[mountAt[topListenersIDKey]]; +} + +/** + * We listen for bubbled touch events on the document object. + * + * Firefox v8.01 (and possibly others) exhibited strange behavior when + * mounting `onmousemove` events at some node that was not the document + * element. The symptoms were that if your mouse is not moving over something + * contained within that mount point (for example on the background) the + * top-level listeners for `onmousemove` won't be called. However, if you + * register the `mousemove` on the document object, then it will of course + * catch all `mousemove`s. This along with iOS quirks, justifies restricting + * top-level listeners to the document object only, at least for these + * movement types of events and possibly all events. + * + * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html + * + * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but + * they bubble to document. + * + * @param {string} registrationName Name of listener (e.g. `onClick`). + * @param {object} mountAt Container where to mount the listener + */ +function listenTo(registrationName, mountAt) { + var isListening = getListeningForDocument(mountAt); + var dependencies = registrationNameDependencies[registrationName]; + + for (var i = 0; i < dependencies.length; i++) { + var dependency = dependencies[i]; + if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { + switch (dependency) { + case TOP_SCROLL: + trapCapturedEvent(TOP_SCROLL, mountAt); + break; + case TOP_FOCUS: + case TOP_BLUR: + trapCapturedEvent(TOP_FOCUS, mountAt); + trapCapturedEvent(TOP_BLUR, mountAt); + // We set the flag for a single dependency later in this function, + // but this ensures we mark both as attached rather than just one. + isListening[TOP_BLUR] = true; + isListening[TOP_FOCUS] = true; + break; + case TOP_CANCEL: + case TOP_CLOSE: + if (isEventSupported(getRawEventName(dependency), true)) { + trapCapturedEvent(dependency, mountAt); + } + break; + case TOP_INVALID: + case TOP_SUBMIT: + case TOP_RESET: + // We listen to them on the target DOM elements. + // Some of them bubble so we don't want them to fire twice. + break; + default: + // By default, listen on the top level to all non-media events. + // Media events don't bubble so adding the listener wouldn't do anything. + var isMediaEvent = mediaEventTypes.indexOf(dependency) !== -1; + if (!isMediaEvent) { + trapBubbledEvent(dependency, mountAt); + } + break; + } + isListening[dependency] = true; + } + } +} + +function isListeningToAllDependencies(registrationName, mountAt) { + var isListening = getListeningForDocument(mountAt); + var dependencies = registrationNameDependencies[registrationName]; + for (var i = 0; i < dependencies.length; i++) { + var dependency = dependencies[i]; + if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { + return false; + } + } + return true; +} + +/** + * Given any node return the first leaf node without children. + * + * @param {DOMElement|DOMTextNode} node + * @return {DOMElement|DOMTextNode} + */ +function getLeafNode(node) { + while (node && node.firstChild) { + node = node.firstChild; + } + return node; +} + +/** + * Get the next sibling within a container. This will walk up the + * DOM if a node's siblings have been exhausted. + * + * @param {DOMElement|DOMTextNode} node + * @return {?DOMElement|DOMTextNode} + */ +function getSiblingNode(node) { + while (node) { + if (node.nextSibling) { + return node.nextSibling; + } + node = node.parentNode; + } +} + +/** + * Get object describing the nodes which contain characters at offset. + * + * @param {DOMElement|DOMTextNode} root + * @param {number} offset + * @return {?object} + */ +function getNodeForCharacterOffset(root, offset) { + var node = getLeafNode(root); + var nodeStart = 0; + var nodeEnd = 0; + + while (node) { + if (node.nodeType === TEXT_NODE) { + nodeEnd = nodeStart + node.textContent.length; + + if (nodeStart <= offset && nodeEnd >= offset) { + return { + node: node, + offset: offset - nodeStart + }; + } + + nodeStart = nodeEnd; + } + + node = getLeafNode(getSiblingNode(node)); + } +} + +/** + * @param {DOMElement} outerNode + * @return {?object} + */ +function getOffsets(outerNode) { + var selection = window.getSelection && window.getSelection(); + + if (!selection || selection.rangeCount === 0) { + return null; + } + + var anchorNode = selection.anchorNode, + anchorOffset = selection.anchorOffset, + focusNode = selection.focusNode, + focusOffset = selection.focusOffset; + + // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the + // up/down buttons on an . Anonymous divs do not seem to + // expose properties, triggering a "Permission denied error" if any of its + // properties are accessed. The only seemingly possible way to avoid erroring + // is to access a property that typically works for non-anonymous divs and + // catch any error that may otherwise arise. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 + + try { + /* eslint-disable no-unused-expressions */ + anchorNode.nodeType; + focusNode.nodeType; + /* eslint-enable no-unused-expressions */ + } catch (e) { + return null; + } + + return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset); +} + +/** + * Returns {start, end} where `start` is the character/codepoint index of + * (anchorNode, anchorOffset) within the textContent of `outerNode`, and + * `end` is the index of (focusNode, focusOffset). + * + * Returns null if you pass in garbage input but we should probably just crash. + * + * Exported only for testing. + */ +function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) { + var length = 0; + var start = -1; + var end = -1; + var indexWithinAnchor = 0; + var indexWithinFocus = 0; + var node = outerNode; + var parentNode = null; + + outer: while (true) { + var next = null; + + while (true) { + if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) { + start = length + anchorOffset; + } + if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) { + end = length + focusOffset; + } + + if (node.nodeType === TEXT_NODE) { + length += node.nodeValue.length; + } + + if ((next = node.firstChild) === null) { + break; + } + // Moving from `node` to its first child `next`. + parentNode = node; + node = next; + } + + while (true) { + if (node === outerNode) { + // If `outerNode` has children, this is always the second time visiting + // it. If it has no children, this is still the first loop, and the only + // valid selection is anchorNode and focusNode both equal to this node + // and both offsets 0, in which case we will have handled above. + break outer; + } + if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) { + start = length; + } + if (parentNode === focusNode && ++indexWithinFocus === focusOffset) { + end = length; + } + if ((next = node.nextSibling) !== null) { + break; + } + node = parentNode; + parentNode = node.parentNode; + } + + // Moving from `node` to its next sibling `next`. + node = next; + } + + if (start === -1 || end === -1) { + // This should never happen. (Would happen if the anchor/focus nodes aren't + // actually inside the passed-in node.) + return null; + } + + return { + start: start, + end: end + }; +} + +/** + * In modern non-IE browsers, we can support both forward and backward + * selections. + * + * Note: IE10+ supports the Selection object, but it does not support + * the `extend` method, which means that even in modern IE, it's not possible + * to programmatically create a backward selection. Thus, for all IE + * versions, we use the old IE API to create our selections. + * + * @param {DOMElement|DOMTextNode} node + * @param {object} offsets + */ +function setOffsets(node, offsets) { + if (!window.getSelection) { + return; + } + + var selection = window.getSelection(); + var length = node[getTextContentAccessor()].length; + var start = Math.min(offsets.start, length); + var end = offsets.end === undefined ? start : Math.min(offsets.end, length); + + // IE 11 uses modern selection, but doesn't support the extend method. + // Flip backward selections, so we can set with a single range. + if (!selection.extend && start > end) { + var temp = end; + end = start; + start = temp; + } + + var startMarker = getNodeForCharacterOffset(node, start); + var endMarker = getNodeForCharacterOffset(node, end); + + if (startMarker && endMarker) { + if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) { + return; + } + var range = document.createRange(); + range.setStart(startMarker.node, startMarker.offset); + selection.removeAllRanges(); + + if (start > end) { + selection.addRange(range); + selection.extend(endMarker.node, endMarker.offset); + } else { + range.setEnd(endMarker.node, endMarker.offset); + selection.addRange(range); + } + } +} + +function isInDocument(node) { + return containsNode(document.documentElement, node); +} + +/** + * @ReactInputSelection: React input selection module. Based on Selection.js, + * but modified to be suitable for react and has a couple of bug fixes (doesn't + * assume buttons have range selections allowed). + * Input selection module for React. + */ + +/** + * @hasSelectionCapabilities: we get the element types that support selection + * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart` + * and `selectionEnd` rows. + */ +function hasSelectionCapabilities(elem) { + var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); + return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true'); +} + +function getSelectionInformation() { + var focusedElem = getActiveElement(); + return { + focusedElem: focusedElem, + selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection$1(focusedElem) : null + }; +} + +/** + * @restoreSelection: If any selection information was potentially lost, + * restore it. This is useful when performing operations that could remove dom + * nodes and place them back in, resulting in focus being lost. + */ +function restoreSelection(priorSelectionInformation) { + var curFocusedElem = getActiveElement(); + var priorFocusedElem = priorSelectionInformation.focusedElem; + var priorSelectionRange = priorSelectionInformation.selectionRange; + if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { + if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) { + setSelection(priorFocusedElem, priorSelectionRange); + } + + // Focusing a node can change the scroll position, which is undesirable + var ancestors = []; + var ancestor = priorFocusedElem; + while (ancestor = ancestor.parentNode) { + if (ancestor.nodeType === ELEMENT_NODE) { + ancestors.push({ + element: ancestor, + left: ancestor.scrollLeft, + top: ancestor.scrollTop + }); + } + } + + if (typeof priorFocusedElem.focus === 'function') { + priorFocusedElem.focus(); + } + + for (var i = 0; i < ancestors.length; i++) { + var info = ancestors[i]; + info.element.scrollLeft = info.left; + info.element.scrollTop = info.top; + } + } +} + +/** + * @getSelection: Gets the selection bounds of a focused textarea, input or + * contentEditable node. + * -@input: Look up selection bounds of this input + * -@return {start: selectionStart, end: selectionEnd} + */ +function getSelection$1(input) { + var selection = void 0; + + if ('selectionStart' in input) { + // Modern browser with input or textarea. + selection = { + start: input.selectionStart, + end: input.selectionEnd + }; + } else { + // Content editable or old IE textarea. + selection = getOffsets(input); + } + + return selection || { start: 0, end: 0 }; +} + +/** + * @setSelection: Sets the selection bounds of a textarea or input and focuses + * the input. + * -@input Set selection bounds of this input or textarea + * -@offsets Object of same form that is returned from get* + */ +function setSelection(input, offsets) { + var start = offsets.start, + end = offsets.end; + + if (end === undefined) { + end = start; + } + + if ('selectionStart' in input) { + input.selectionStart = start; + input.selectionEnd = Math.min(end, input.value.length); + } else { + setOffsets(input, offsets); + } +} + +var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; + +var eventTypes$3 = { + select: { + phasedRegistrationNames: { + bubbled: 'onSelect', + captured: 'onSelectCapture' + }, + dependencies: [TOP_BLUR, TOP_CONTEXT_MENU, TOP_FOCUS, TOP_KEY_DOWN, TOP_KEY_UP, TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_SELECTION_CHANGE] + } +}; + +var activeElement$1 = null; +var activeElementInst$1 = null; +var lastSelection = null; +var mouseDown = false; + +/** + * Get an object which is a unique representation of the current selection. + * + * The return value will not be consistent across nodes or browsers, but + * two identical selections on the same node will return identical objects. + * + * @param {DOMElement} node + * @return {object} + */ +function getSelection(node) { + if ('selectionStart' in node && hasSelectionCapabilities(node)) { + return { + start: node.selectionStart, + end: node.selectionEnd + }; + } else if (window.getSelection) { + var selection = window.getSelection(); + return { + anchorNode: selection.anchorNode, + anchorOffset: selection.anchorOffset, + focusNode: selection.focusNode, + focusOffset: selection.focusOffset + }; + } +} + +/** + * Poll selection to see whether it's changed. + * + * @param {object} nativeEvent + * @return {?SyntheticEvent} + */ +function constructSelectEvent(nativeEvent, nativeEventTarget) { + // Ensure we have the right element, and that the user is not dragging a + // selection (this matches native `select` event behavior). In HTML5, select + // fires only on input and textarea thus if there's no focused element we + // won't dispatch. + if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement()) { + return null; + } + + // Only fire when selection has actually changed. + var currentSelection = getSelection(activeElement$1); + if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { + lastSelection = currentSelection; + + var syntheticEvent = SyntheticEvent$1.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget); + + syntheticEvent.type = 'select'; + syntheticEvent.target = activeElement$1; + + accumulateTwoPhaseDispatches(syntheticEvent); + + return syntheticEvent; + } + + return null; +} + +/** + * This plugin creates an `onSelect` event that normalizes select events + * across form elements. + * + * Supported elements are: + * - input (see `isTextInputElement`) + * - textarea + * - contentEditable + * + * This differs from native browser implementations in the following ways: + * - Fires on contentEditable fields as well as inputs. + * - Fires for collapsed selection. + * - Fires after user input. + */ +var SelectEventPlugin = { + eventTypes: eventTypes$3, + + extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var doc = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget.document : nativeEventTarget.nodeType === DOCUMENT_NODE ? nativeEventTarget : nativeEventTarget.ownerDocument; + // Track whether all listeners exists for this plugin. If none exist, we do + // not extract events. See #3639. + if (!doc || !isListeningToAllDependencies('onSelect', doc)) { + return null; + } + + var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window; + + switch (topLevelType) { + // Track the input node that has focus. + case TOP_FOCUS: + if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { + activeElement$1 = targetNode; + activeElementInst$1 = targetInst; + lastSelection = null; + } + break; + case TOP_BLUR: + activeElement$1 = null; + activeElementInst$1 = null; + lastSelection = null; + break; + // Don't fire the event while the user is dragging. This matches the + // semantics of the native select event. + case TOP_MOUSE_DOWN: + mouseDown = true; + break; + case TOP_CONTEXT_MENU: + case TOP_MOUSE_UP: + mouseDown = false; + return constructSelectEvent(nativeEvent, nativeEventTarget); + // Chrome and IE fire non-standard event when selection is changed (and + // sometimes when it hasn't). IE's event fires out of order with respect + // to key and input events on deletion, so we discard it. + // + // Firefox doesn't support selectionchange, so check selection status + // after each key entry. The selection changes after keydown and before + // keyup, but we check on keydown as well in the case of holding down a + // key, when multiple keydown events are fired but only one keyup is. + // This is also our approach for IE handling, for the reason above. + case TOP_SELECTION_CHANGE: + if (skipSelectionChangeEvent) { + break; + } + // falls through + case TOP_KEY_DOWN: + case TOP_KEY_UP: + return constructSelectEvent(nativeEvent, nativeEventTarget); + } + + return null; + } +}; + +/** + * Inject modules for resolving DOM hierarchy and plugin ordering. + */ +injection.injectEventPluginOrder(DOMEventPluginOrder); +injection$1.injectComponentTree(ReactDOMComponentTree); + +/** + * Some important event plugins included by default (without having to require + * them). + */ +injection.injectEventPluginsByName({ + SimpleEventPlugin: SimpleEventPlugin, + EnterLeaveEventPlugin: EnterLeaveEventPlugin, + ChangeEventPlugin: ChangeEventPlugin, + SelectEventPlugin: SelectEventPlugin, + BeforeInputEventPlugin: BeforeInputEventPlugin +}); + +// We capture a local reference to any global, in case it gets polyfilled after +// this module is initially evaluated. +// We want to be using a consistent implementation. + +var localRequestAnimationFrame$1 = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : undefined; + +/** + * A scheduling library to allow scheduling work with more granular priority and + * control than requestAnimationFrame and requestIdleCallback. + * Current TODO items: + * X- Pull out the scheduleWork polyfill built into React + * X- Initial test coverage + * X- Support for multiple callbacks + * - Support for two priorities; serial and deferred + * - Better test coverage + * - Better docblock + * - Polish documentation, API + */ + +// This is a built-in polyfill for requestIdleCallback. It works by scheduling +// a requestAnimationFrame, storing the time for the start of the frame, then +// scheduling a postMessage which gets scheduled after paint. Within the +// postMessage handler do as much work as possible until time + frame rate. +// By separating the idle call into a separate event tick we ensure that +// layout, paint and other browser work is counted against the available time. +// The frame rate is dynamically adjusted. + +// We capture a local reference to any global, in case it gets polyfilled after +// this module is initially evaluated. +// We want to be using a consistent implementation. +var localDate = Date; +var localSetTimeout = setTimeout; +var localClearTimeout = clearTimeout; + +var hasNativePerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; + +var now$1 = void 0; +if (hasNativePerformanceNow) { + var Performance = performance; + now$1 = function () { + return Performance.now(); + }; +} else { + now$1 = function () { + return localDate.now(); + }; +} + +var scheduleWork = void 0; +var cancelScheduledWork = void 0; + +if (!ExecutionEnvironment.canUseDOM) { + var timeoutIds = new Map(); + + scheduleWork = function (callback, options) { + // keeping return type consistent + var callbackConfig = { + scheduledCallback: callback, + timeoutTime: 0, + next: null, + prev: null + }; + var timeoutId = localSetTimeout(function () { + callback({ + timeRemaining: function () { + return Infinity; + }, + + didTimeout: false + }); + }); + timeoutIds.set(callback, timeoutId); + return callbackConfig; + }; + cancelScheduledWork = function (callbackId) { + var callback = callbackId.scheduledCallback; + var timeoutId = timeoutIds.get(callback); + timeoutIds.delete(callbackId); + localClearTimeout(timeoutId); + }; +} else { + { + if (typeof localRequestAnimationFrame$1 !== 'function') { + warning(false, 'React depends on requestAnimationFrame. Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills'); + } + } + + var localRequestAnimationFrame = typeof localRequestAnimationFrame$1 === 'function' ? localRequestAnimationFrame$1 : function (callback) { + invariant(false, 'React depends on requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills'); + }; + + var headOfPendingCallbacksLinkedList = null; + var tailOfPendingCallbacksLinkedList = null; + + // We track what the next soonest timeoutTime is, to be able to quickly tell + // if none of the scheduled callbacks have timed out. + var nextSoonestTimeoutTime = -1; + + var isIdleScheduled = false; + var isAnimationFrameScheduled = false; + + var frameDeadline = 0; + // We start out assuming that we run at 30fps but then the heuristic tracking + // will adjust this value to a faster fps if we get more frequent animation + // frames. + var previousFrameTime = 33; + var activeFrameTime = 33; + + var frameDeadlineObject = { + didTimeout: false, + timeRemaining: function () { + var remaining = frameDeadline - now$1(); + return remaining > 0 ? remaining : 0; + } + }; + + /** + * Handles the case where a callback errors: + * - don't catch the error, because this changes debugging behavior + * - do start a new postMessage callback, to call any remaining callbacks, + * - but only if there is an error, so there is not extra overhead. + */ + var callUnsafely = function (callbackConfig, arg) { + var callback = callbackConfig.scheduledCallback; + var finishedCalling = false; + try { + callback(arg); + finishedCalling = true; + } finally { + // always remove it from linked list + cancelScheduledWork(callbackConfig); + + if (!finishedCalling) { + // an error must have been thrown + isIdleScheduled = true; + window.postMessage(messageKey, '*'); + } + } + }; + + /** + * Checks for timed out callbacks, runs them, and then checks again to see if + * any more have timed out. + * Keeps doing this until there are none which have currently timed out. + */ + var callTimedOutCallbacks = function () { + if (headOfPendingCallbacksLinkedList === null) { + return; + } + + var currentTime = now$1(); + // TODO: this would be more efficient if deferred callbacks are stored in + // min heap. + // Or in a linked list with links for both timeoutTime order and insertion + // order. + // For now an easy compromise is the current approach: + // Keep a pointer to the soonest timeoutTime, and check that first. + // If it has not expired, we can skip traversing the whole list. + // If it has expired, then we step through all the callbacks. + if (nextSoonestTimeoutTime === -1 || nextSoonestTimeoutTime > currentTime) { + // We know that none of them have timed out yet. + return; + } + // NOTE: we intentionally wait to update the nextSoonestTimeoutTime until + // after successfully calling any timed out callbacks. + // If a timed out callback throws an error, we could get stuck in a state + // where the nextSoonestTimeoutTime was set wrong. + var updatedNextSoonestTimeoutTime = -1; // we will update nextSoonestTimeoutTime below + var timedOutCallbacks = []; + + // iterate once to find timed out callbacks and find nextSoonestTimeoutTime + var currentCallbackConfig = headOfPendingCallbacksLinkedList; + while (currentCallbackConfig !== null) { + var _timeoutTime = currentCallbackConfig.timeoutTime; + if (_timeoutTime !== -1 && _timeoutTime <= currentTime) { + // it has timed out! + timedOutCallbacks.push(currentCallbackConfig); + } else { + if (_timeoutTime !== -1 && (updatedNextSoonestTimeoutTime === -1 || _timeoutTime < updatedNextSoonestTimeoutTime)) { + updatedNextSoonestTimeoutTime = _timeoutTime; + } + } + currentCallbackConfig = currentCallbackConfig.next; + } + + if (timedOutCallbacks.length > 0) { + frameDeadlineObject.didTimeout = true; + for (var i = 0, len = timedOutCallbacks.length; i < len; i++) { + callUnsafely(timedOutCallbacks[i], frameDeadlineObject); + } + } + + // NOTE: we intentionally wait to update the nextSoonestTimeoutTime until + // after successfully calling any timed out callbacks. + nextSoonestTimeoutTime = updatedNextSoonestTimeoutTime; + }; + + // We use the postMessage trick to defer idle work until after the repaint. + var messageKey = '__reactIdleCallback$' + Math.random().toString(36).slice(2); + var idleTick = function (event) { + if (event.source !== window || event.data !== messageKey) { + return; + } + isIdleScheduled = false; + + if (headOfPendingCallbacksLinkedList === null) { + return; + } + + // First call anything which has timed out, until we have caught up. + callTimedOutCallbacks(); + + var currentTime = now$1(); + // Next, as long as we have idle time, try calling more callbacks. + while (frameDeadline - currentTime > 0 && headOfPendingCallbacksLinkedList !== null) { + var latestCallbackConfig = headOfPendingCallbacksLinkedList; + frameDeadlineObject.didTimeout = false; + // callUnsafely will remove it from the head of the linked list + callUnsafely(latestCallbackConfig, frameDeadlineObject); + currentTime = now$1(); + } + if (headOfPendingCallbacksLinkedList !== null) { + if (!isAnimationFrameScheduled) { + // Schedule another animation callback so we retry later. + isAnimationFrameScheduled = true; + localRequestAnimationFrame(animationTick); + } + } + }; + // Assumes that we have addEventListener in this environment. Might need + // something better for old IE. + window.addEventListener('message', idleTick, false); + + var animationTick = function (rafTime) { + isAnimationFrameScheduled = false; + var nextFrameTime = rafTime - frameDeadline + activeFrameTime; + if (nextFrameTime < activeFrameTime && previousFrameTime < activeFrameTime) { + if (nextFrameTime < 8) { + // Defensive coding. We don't support higher frame rates than 120hz. + // If we get lower than that, it is probably a bug. + nextFrameTime = 8; + } + // If one frame goes long, then the next one can be short to catch up. + // If two frames are short in a row, then that's an indication that we + // actually have a higher frame rate than what we're currently optimizing. + // We adjust our heuristic dynamically accordingly. For example, if we're + // running on 120hz display or 90hz VR display. + // Take the max of the two in case one of them was an anomaly due to + // missed frame deadlines. + activeFrameTime = nextFrameTime < previousFrameTime ? previousFrameTime : nextFrameTime; + } else { + previousFrameTime = nextFrameTime; + } + frameDeadline = rafTime + activeFrameTime; + if (!isIdleScheduled) { + isIdleScheduled = true; + window.postMessage(messageKey, '*'); + } + }; + + scheduleWork = function (callback, options) /* CallbackConfigType */{ + var timeoutTime = -1; + if (options != null && typeof options.timeout === 'number') { + timeoutTime = now$1() + options.timeout; + } + if (nextSoonestTimeoutTime === -1 || timeoutTime !== -1 && timeoutTime < nextSoonestTimeoutTime) { + nextSoonestTimeoutTime = timeoutTime; + } + + var scheduledCallbackConfig = { + scheduledCallback: callback, + timeoutTime: timeoutTime, + prev: null, + next: null + }; + if (headOfPendingCallbacksLinkedList === null) { + // Make this callback the head and tail of our list + headOfPendingCallbacksLinkedList = scheduledCallbackConfig; + tailOfPendingCallbacksLinkedList = scheduledCallbackConfig; + } else { + // Add latest callback as the new tail of the list + scheduledCallbackConfig.prev = tailOfPendingCallbacksLinkedList; + // renaming for clarity + var oldTailOfPendingCallbacksLinkedList = tailOfPendingCallbacksLinkedList; + if (oldTailOfPendingCallbacksLinkedList !== null) { + oldTailOfPendingCallbacksLinkedList.next = scheduledCallbackConfig; + } + tailOfPendingCallbacksLinkedList = scheduledCallbackConfig; + } + + if (!isAnimationFrameScheduled) { + // If rAF didn't already schedule one, we need to schedule a frame. + // TODO: If this rAF doesn't materialize because the browser throttles, we + // might want to still have setTimeout trigger scheduleWork as a backup to ensure + // that we keep performing work. + isAnimationFrameScheduled = true; + localRequestAnimationFrame(animationTick); + } + return scheduledCallbackConfig; + }; + + cancelScheduledWork = function (callbackConfig /* CallbackConfigType */ + ) { + if (callbackConfig.prev === null && headOfPendingCallbacksLinkedList !== callbackConfig) { + // this callbackConfig has already been cancelled. + // cancelScheduledWork should be idempotent, a no-op after first call. + return; + } + + /** + * There are four possible cases: + * - Head/nodeToRemove/Tail -> null + * In this case we set Head and Tail to null. + * - Head -> ... middle nodes... -> Tail/nodeToRemove + * In this case we point the middle.next to null and put middle as the new + * Tail. + * - Head/nodeToRemove -> ...middle nodes... -> Tail + * In this case we point the middle.prev at null and move the Head to + * middle. + * - Head -> ... ?some nodes ... -> nodeToRemove -> ... ?some nodes ... -> Tail + * In this case we point the Head.next to the Tail and the Tail.prev to + * the Head. + */ + var next = callbackConfig.next; + var prev = callbackConfig.prev; + callbackConfig.next = null; + callbackConfig.prev = null; + if (next !== null) { + // we have a next + + if (prev !== null) { + // we have a prev + + // callbackConfig is somewhere in the middle of a list of 3 or more nodes. + prev.next = next; + next.prev = prev; + return; + } else { + // there is a next but not a previous one; + // callbackConfig is the head of a list of 2 or more other nodes. + next.prev = null; + headOfPendingCallbacksLinkedList = next; + return; + } + } else { + // there is no next callback config; this must the tail of the list + + if (prev !== null) { + // we have a prev + + // callbackConfig is the tail of a list of 2 or more other nodes. + prev.next = null; + tailOfPendingCallbacksLinkedList = prev; + return; + } else { + // there is no previous callback config; + // callbackConfig is the only thing in the linked list, + // so both head and tail point to it. + headOfPendingCallbacksLinkedList = null; + tailOfPendingCallbacksLinkedList = null; + return; + } + } + }; +} + +var didWarnSelectedSetOnOption = false; + +function flattenChildren(children) { + var content = ''; + + // Flatten children and warn if they aren't strings or numbers; + // invalid types are ignored. + // We can silently skip them because invalid DOM nesting warning + // catches these cases in Fiber. + React.Children.forEach(children, function (child) { + if (child == null) { + return; + } + if (typeof child === 'string' || typeof child === 'number') { + content += child; + } + }); + + return content; +} + +/** + * Implements an