From ffb2a593b1281b42e2f1398f3133ae44313c81ef Mon Sep 17 00:00:00 2001 From: tangjinzhou <415800467@qq.com> Date: Sat, 12 Jan 2019 11:33:27 +0800 Subject: [PATCH] style: lint add semi and prettier --- .eslintignore | 4 + .eslintrc | 7 +- .prettierignore | 9 + .prettierrc | 19 + .stylelintrc | 3 +- antd-tools/cli/index.js | 22 +- antd-tools/cli/run.js | 26 +- antd-tools/getBabelCommonConfig.js | 46 +- antd-tools/getWebpackConfig.js | 137 +- antd-tools/gulpfile.js | 432 ++--- antd-tools/postcssConfig.js | 15 +- antd-tools/replaceLib.js | 22 +- antd-tools/runCmd.js | 18 +- antd-tools/transformLess.js | 45 +- antd-tools/utils/get-npm-args.js | 16 +- antd-tools/utils/getChangelog.js | 31 +- antd-tools/utils/getRunCmdEnv.js | 22 +- components/_util/BaseMixin.js | 26 +- components/_util/ContainerRender.jsx | 68 +- components/_util/Dom/addEventListener.js | 6 +- components/_util/Dom/class-util.js | 34 +- components/_util/Dom/contains.js | 10 +- components/_util/FormDecoratorDirective.js | 9 +- components/_util/KeyCode.js | 50 +- components/_util/StateMixin.js | 10 +- components/_util/antDirective.js | 10 +- components/_util/antInputDirective.js | 67 +- components/_util/callMoment.js | 4 +- components/_util/createChainedFunction.js | 12 +- components/_util/css-animation/Event.js | 92 +- components/_util/css-animation/index.js | 178 +- components/_util/env.js | 8 +- components/_util/getLocale.js | 24 +- components/_util/getRequestAnimationFrame.js | 52 +- components/_util/getScroll.js | 16 +- components/_util/getScrollBarSize.js | 48 +- components/_util/getTransitionProps.js | 32 +- components/_util/interopDefault.js | 4 +- components/_util/isCssAnimationSupported.js | 22 +- components/_util/isFlexSupported.js | 10 +- components/_util/isNumeric.js | 8 +- components/_util/openAnimation.js | 70 +- components/_util/props-util.js | 340 ++-- components/_util/proxyComponent.jsx | 65 +- components/_util/raf.js | 34 +- components/_util/requestAnimationTimeout.js | 23 +- components/_util/store/PropTypes.js | 4 +- components/_util/store/Provider.jsx | 13 +- components/_util/store/connect.jsx | 109 +- components/_util/store/create.js | 30 +- components/_util/store/index.js | 6 +- components/_util/throttleByAnimationFrame.js | 46 +- components/_util/triggerEvent.js | 8 +- components/_util/vnode.js | 115 +- components/_util/vue-types/index.js | 243 +-- components/_util/vue-types/utils.js | 160 +- components/_util/warning.js | 10 +- components/_util/wave.jsx | 174 +- components/affix/__tests__/demo.test.js | 4 +- components/affix/__tests__/index.test.js | 139 +- components/affix/demo/index.vue | 16 +- components/affix/index.jsx | 263 ++- components/alert/__tests__/demo.test.js | 4 +- components/alert/__tests__/index.test.js | 92 +- components/alert/demo/index.vue | 26 +- components/alert/index.jsx | 124 +- components/anchor/Anchor.jsx | 235 ++- components/anchor/AnchorLink.jsx | 58 +- components/anchor/__tests__/Anchor.test.js | 362 +++-- components/anchor/__tests__/demo.test.js | 4 +- components/anchor/demo/index.vue | 16 +- components/anchor/index.jsx | 20 +- components/auto-complete/InputElement.jsx | 48 +- .../auto-complete/__tests__/demo.test.js | 4 +- .../auto-complete/__tests__/index.test.js | 68 +- components/auto-complete/demo/index.vue | 22 +- components/auto-complete/index.jsx | 118 +- components/avatar/Avatar.jsx | 136 +- components/avatar/__tests__/Avatar.test.js | 86 +- components/avatar/__tests__/demo.test.js | 4 +- components/avatar/demo/index.vue | 18 +- components/avatar/index.js | 10 +- components/back-top/__tests__/demo.test.js | 4 +- components/back-top/__tests__/index.test.js | 22 +- components/back-top/demo/index.vue | 14 +- components/back-top/index.jsx | 132 +- components/badge/Badge.jsx | 176 +- components/badge/ScrollNumber.jsx | 146 +- components/badge/__tests__/demo.test.js | 4 +- components/badge/__tests__/index.test.js | 105 +- components/badge/demo/index.vue | 24 +- components/badge/index.js | 11 +- components/breadcrumb/Breadcrumb.jsx | 85 +- components/breadcrumb/BreadcrumbItem.jsx | 28 +- .../breadcrumb/__tests__/Breadcrumb.test.js | 102 +- components/breadcrumb/__tests__/demo.test.js | 4 +- components/breadcrumb/demo/index.vue | 18 +- components/breadcrumb/index.js | 17 +- components/button/__tests__/demo.test.js | 4 +- components/button/__tests__/index.test.js | 265 +-- components/button/button-group.jsx | 36 +- components/button/button.jsx | 144 +- components/button/buttonTypes.js | 4 +- components/button/demo/index.vue | 28 +- components/button/index.js | 17 +- components/calendar/Constants.js | 2 +- components/calendar/Header.jsx | 141 +- components/calendar/__tests__/demo.test.js | 4 +- components/calendar/__tests__/index.test.js | 295 ++-- components/calendar/demo/index.vue | 18 +- components/calendar/index.jsx | 211 ++- components/calendar/locale/ar_EG.js | 4 +- components/calendar/locale/bg_BG.js | 4 +- components/calendar/locale/ca_ES.js | 4 +- components/calendar/locale/cs_CZ.js | 4 +- components/calendar/locale/da_DK.js | 4 +- components/calendar/locale/de_DE.js | 4 +- components/calendar/locale/el_GR.js | 4 +- components/calendar/locale/en_GB.js | 4 +- components/calendar/locale/en_US.js | 4 +- components/calendar/locale/es_ES.js | 4 +- components/calendar/locale/et_EE.js | 4 +- components/calendar/locale/fa_IR.js | 4 +- components/calendar/locale/fi_FI.js | 4 +- components/calendar/locale/fr_BE.js | 4 +- components/calendar/locale/fr_FR.js | 4 +- components/calendar/locale/he_IL.js | 4 +- components/calendar/locale/hu_HU.js | 4 +- components/calendar/locale/id_ID.js | 4 +- components/calendar/locale/is_IS.js | 4 +- components/calendar/locale/it_IT.js | 4 +- components/calendar/locale/ja_JP.js | 4 +- components/calendar/locale/ko_KR.js | 4 +- components/calendar/locale/ku_IQ.js | 4 +- components/calendar/locale/mn_MN.js | 4 +- components/calendar/locale/nb_NO.js | 4 +- components/calendar/locale/nl_BE.js | 4 +- components/calendar/locale/nl_NL.js | 4 +- components/calendar/locale/pl_PL.js | 4 +- components/calendar/locale/pt_BR.js | 4 +- components/calendar/locale/pt_PT.js | 4 +- components/calendar/locale/ru_RU.js | 4 +- components/calendar/locale/sk_SK.js | 4 +- components/calendar/locale/sl_SI.js | 4 +- components/calendar/locale/sr_RS.js | 4 +- components/calendar/locale/sv_SE.js | 4 +- components/calendar/locale/th_TH.js | 4 +- components/calendar/locale/tr_TR.js | 4 +- components/calendar/locale/uk_UA.js | 4 +- components/calendar/locale/vi_VN.js | 4 +- components/calendar/locale/zh_CN.js | 4 +- components/calendar/locale/zh_TW.js | 4 +- components/card/Card.jsx | 173 +- components/card/Grid.jsx | 18 +- components/card/Meta.jsx | 43 +- components/card/__tests__/demo.test.js | 4 +- components/card/__tests__/index.test.js | 78 +- components/card/demo/index.vue | 32 +- components/card/index.js | 22 +- components/carousel/__tests__/demo.test.js | 4 +- components/carousel/__tests__/index.test.js | 92 +- components/carousel/demo/index.vue | 24 +- components/carousel/index.jsx | 99 +- components/cascader/__tests__/demo.test.js | 4 +- components/cascader/__tests__/index.test.js | 382 +++-- components/cascader/demo/index.vue | 34 +- components/cascader/index.jsx | 452 +++--- components/checkbox/Checkbox.jsx | 80 +- components/checkbox/Group.jsx | 72 +- .../checkbox/__tests__/checkbox.test.js | 27 +- components/checkbox/__tests__/demo.test.js | 4 +- components/checkbox/__tests__/group.test.js | 175 +- components/checkbox/demo/index.vue | 22 +- components/checkbox/index.js | 17 +- components/col/index.js | 10 +- components/collapse/Collapse.jsx | 27 +- components/collapse/CollapsePanel.jsx | 29 +- components/collapse/__tests__/demo.test.js | 4 +- components/collapse/demo/index.vue | 22 +- components/collapse/index.js | 17 +- components/comment/__tests__/demo.test.js | 4 +- components/comment/demo/index.vue | 18 +- components/comment/index.jsx | 60 +- components/config-provider/demo/index.vue | 10 +- components/config-provider/index.jsx | 22 +- components/date-picker/RangePicker.jsx | 396 ++--- components/date-picker/WeekPicker.jsx | 196 +-- .../date-picker/__tests__/DatePicker.test.js | 174 +- .../date-picker/__tests__/MonthPicker.test.js | 35 +- .../date-picker/__tests__/RangePicker.test.js | 551 ++++--- .../date-picker/__tests__/WeekPicker.test.js | 31 +- components/date-picker/__tests__/demo.test.js | 4 +- .../date-picker/__tests__/other.test.js | 62 +- .../date-picker/__tests__/showTime.test.js | 306 ++-- components/date-picker/__tests__/utils.js | 37 +- components/date-picker/createPicker.js | 225 ++- components/date-picker/demo/index.vue | 34 +- components/date-picker/index.js | 41 +- components/date-picker/interface.js | 41 +- components/date-picker/locale/ar_EG.js | 8 +- components/date-picker/locale/bg_BG.js | 12 +- components/date-picker/locale/ca_ES.js | 12 +- components/date-picker/locale/cs_CZ.js | 12 +- components/date-picker/locale/da_DK.js | 8 +- components/date-picker/locale/de_DE.js | 12 +- components/date-picker/locale/el_GR.js | 12 +- components/date-picker/locale/en_GB.js | 12 +- components/date-picker/locale/en_US.js | 12 +- components/date-picker/locale/es_ES.js | 12 +- components/date-picker/locale/et_EE.js | 12 +- components/date-picker/locale/example.json | 5 +- components/date-picker/locale/fa_IR.js | 12 +- components/date-picker/locale/fi_FI.js | 12 +- components/date-picker/locale/fr_BE.js | 12 +- components/date-picker/locale/fr_FR.js | 12 +- components/date-picker/locale/he_IL.js | 8 +- components/date-picker/locale/hu_HU.js | 8 +- components/date-picker/locale/id_ID.js | 8 +- components/date-picker/locale/is_IS.js | 12 +- components/date-picker/locale/it_IT.js | 12 +- components/date-picker/locale/ja_JP.js | 12 +- components/date-picker/locale/ko_KR.js | 12 +- components/date-picker/locale/ku_IQ.js | 12 +- components/date-picker/locale/mn_MN.js | 8 +- components/date-picker/locale/nb_NO.js | 12 +- components/date-picker/locale/nl_BE.js | 12 +- components/date-picker/locale/nl_NL.js | 12 +- components/date-picker/locale/pl_PL.js | 12 +- components/date-picker/locale/pt_BR.js | 12 +- components/date-picker/locale/pt_PT.js | 12 +- components/date-picker/locale/ru_RU.js | 12 +- components/date-picker/locale/sk_SK.js | 12 +- components/date-picker/locale/sl_SI.js | 6 +- components/date-picker/locale/sr_RS.js | 12 +- components/date-picker/locale/sv_SE.js | 12 +- components/date-picker/locale/th_TH.js | 21 +- components/date-picker/locale/tr_TR.js | 12 +- components/date-picker/locale/uk_UA.js | 12 +- components/date-picker/locale/vi_VN.js | 12 +- components/date-picker/locale/zh_CN.js | 14 +- components/date-picker/locale/zh_TW.js | 14 +- components/date-picker/wrapPicker.js | 131 +- components/divider/__tests__/demo.test.js | 4 +- components/divider/demo/index.vue | 16 +- components/divider/index.jsx | 31 +- components/drawer/__tests__/Drawer.test.js | 80 +- .../drawer/__tests__/DrawerEvent.test.js | 134 +- .../drawer/__tests__/MultiDrawer.test.js | 128 +- components/drawer/__tests__/demo.test.js | 4 +- components/drawer/demo/descriptionItem.vue | 2 +- components/drawer/demo/index.vue | 22 +- components/drawer/index.jsx | 169 +- components/dropdown/__tests__/demo.test.js | 4 +- .../__tests__/dropdown-button.test.js | 44 +- components/dropdown/demo/index.vue | 28 +- components/dropdown/dropdown-button.jsx | 80 +- components/dropdown/dropdown.jsx | 102 +- components/dropdown/getDropdownProps.js | 13 +- components/dropdown/index.js | 20 +- components/form/Form.jsx | 155 +- components/form/FormItem.jsx | 425 ++--- components/form/__tests__/demo.test.js | 4 +- components/form/__tests__/index.test.js | 39 +- components/form/__tests__/label.test.js | 206 ++- components/form/__tests__/message.test.js | 93 +- components/form/constants.jsx | 4 +- components/form/demo/advanced-search.vue | 18 +- components/form/demo/coordinated.vue | 14 +- .../form/demo/customized-form-controls.vue | 48 +- components/form/demo/dynamic-form-item.vue | 32 +- components/form/demo/dynamic-rule.vue | 18 +- components/form/demo/form-in-modal.vue | 24 +- components/form/demo/global-state.vue | 20 +- components/form/demo/horizontal-login.vue | 24 +- components/form/demo/index.vue | 70 +- components/form/demo/layout.vue | 14 +- components/form/demo/normal-login.vue | 10 +- components/form/demo/register.vue | 38 +- .../form/demo/time-related-controls.vue | 22 +- components/form/demo/validate-other.vue | 18 +- components/form/demo/validate-static.vue | 4 +- components/form/demo/without-form-create.vue | 10 +- components/form/index.jsx | 30 +- components/grid/Col.jsx | 53 +- components/grid/Row.jsx | 111 +- components/grid/__tests__/demo.test.js | 4 +- components/grid/__tests__/index.test.js | 42 +- components/grid/demo/index.vue | 32 +- components/grid/index.js | 9 +- components/icon/IconFont.jsx | 52 +- components/icon/__tests__/demo.test.js | 4 +- components/icon/__tests__/index.test.js | 265 +-- components/icon/demo/index.vue | 20 +- components/icon/index.js | 123 +- components/icon/twoTonePrimaryColor.js | 12 +- components/icon/utils.js | 46 +- components/index.js | 161 +- .../input-number/__tests__/demo.test.js | 4 +- .../input-number/__tests__/index.test.js | 6 +- components/input-number/demo/index.vue | 20 +- components/input-number/index.jsx | 54 +- components/input/Group.jsx | 26 +- components/input/Input.jsx | 175 +- components/input/Search.jsx | 100 +- components/input/TextArea.jsx | 155 +- components/input/__tests__/Search.test.js | 72 +- components/input/__tests__/demo.test.js | 4 +- components/input/__tests__/index.test.js | 141 +- components/input/calculateNodeHeight.js | 88 +- components/input/demo/index.vue | 28 +- components/input/index.js | 34 +- components/input/inputProps.js | 8 +- components/layout/Sider.jsx | 172 +- components/layout/__tests__/demo.test.js | 4 +- components/layout/__tests__/index.test.js | 108 +- components/layout/demo/index.vue | 38 +- components/layout/index.js | 22 +- components/layout/layout.jsx | 110 +- components/list/Item.jsx | 93 +- components/list/__tests__/demo.test.js | 4 +- components/list/__tests__/empty.test.js | 16 +- components/list/__tests__/index.test.js | 37 +- components/list/__tests__/loading.test.js | 67 +- components/list/demo/index.vue | 26 +- components/list/index.jsx | 199 ++- components/locale-provider/LocaleReceiver.jsx | 45 +- .../locale-provider/__tests__/demo.test.js | 4 +- .../locale-provider/__tests__/index.test.js | 273 ++-- components/locale-provider/ar_EG.js | 10 +- components/locale-provider/bg_BG.js | 10 +- components/locale-provider/ca_ES.js | 10 +- components/locale-provider/cs_CZ.js | 10 +- components/locale-provider/da_DK.js | 10 +- components/locale-provider/de_DE.js | 10 +- components/locale-provider/default.js | 10 +- components/locale-provider/demo/index.vue | 14 +- components/locale-provider/el_GR.js | 10 +- components/locale-provider/en_GB.js | 10 +- components/locale-provider/en_US.js | 4 +- components/locale-provider/es_ES.js | 10 +- components/locale-provider/et_EE.js | 10 +- components/locale-provider/fa_IR.js | 10 +- components/locale-provider/fi_FI.js | 10 +- components/locale-provider/fr_BE.js | 10 +- components/locale-provider/fr_FR.js | 10 +- components/locale-provider/he_IL.js | 10 +- components/locale-provider/hu_HU.js | 10 +- components/locale-provider/id_ID.js | 10 +- components/locale-provider/index.jsx | 64 +- components/locale-provider/is_IS.js | 10 +- components/locale-provider/it_IT.js | 10 +- components/locale-provider/ja_JP.js | 10 +- components/locale-provider/ko_KR.js | 10 +- components/locale-provider/ku_IQ.js | 10 +- components/locale-provider/mn_MN.js | 10 +- components/locale-provider/nb_NO.js | 10 +- components/locale-provider/ne-NP.js | 10 +- components/locale-provider/nl_BE.js | 10 +- components/locale-provider/nl_NL.js | 10 +- components/locale-provider/pl_PL.js | 10 +- components/locale-provider/pt_BR.js | 10 +- components/locale-provider/pt_PT.js | 10 +- components/locale-provider/ru_RU.js | 10 +- components/locale-provider/sk_SK.js | 10 +- components/locale-provider/sl_SI.js | 10 +- components/locale-provider/sr_RS.js | 10 +- components/locale-provider/sv_SE.js | 10 +- components/locale-provider/th_TH.js | 10 +- components/locale-provider/tr_TR.js | 10 +- components/locale-provider/uk_UA.js | 10 +- components/locale-provider/vi_VN.js | 10 +- components/locale-provider/zh_CN.js | 10 +- components/locale-provider/zh_TW.js | 10 +- components/menu/MenuItem.jsx | 38 +- components/menu/__tests__/demo.test.js | 4 +- components/menu/__tests__/index.test.js | 826 +++++----- components/menu/demo/index.vue | 26 +- components/menu/index.jsx | 249 +-- components/message/__tests__/demo.test.js | 4 +- components/message/__tests__/index.test.js | 204 +-- components/message/demo/index.vue | 20 +- components/message/index.js | 155 +- components/modal/ActionButton.jsx | 76 +- components/modal/ConfirmDialog.jsx | 87 +- components/modal/Modal.jsx | 128 +- components/modal/__tests__/Modal.test.js | 72 +- components/modal/__tests__/confirm.test.js | 113 +- components/modal/__tests__/demo.test.js | 4 +- components/modal/confirm.js | 65 +- components/modal/demo/index.vue | 30 +- components/modal/index.js | 66 +- components/modal/locale.js | 14 +- .../notification/__tests__/demo.test.js | 4 +- .../notification/__tests__/index.test.js | 94 +- .../notification/__tests__/placement.test.js | 176 +- components/notification/demo/index.vue | 26 +- components/notification/index.js | 167 +- components/pagination/MiniSelect.jsx | 16 +- components/pagination/Pagination.jsx | 84 +- components/pagination/__tests__/demo.test.js | 4 +- components/pagination/demo/index.vue | 30 +- components/pagination/index.js | 12 +- components/popconfirm/__tests__/demo.test.js | 4 +- components/popconfirm/__tests__/index.test.js | 99 +- components/popconfirm/demo/index.vue | 20 +- components/popconfirm/index.jsx | 161 +- components/popover/__tests__/demo.test.js | 4 +- components/popover/__tests__/index.test.js | 60 +- components/popover/demo/index.vue | 22 +- components/popover/index.jsx | 57 +- components/progress/__tests__/demo.test.js | 4 +- components/progress/__tests__/index.test.js | 76 +- components/progress/demo/index.vue | 30 +- components/progress/index.jsx | 12 +- components/progress/progress.jsx | 126 +- components/radio/Group.jsx | 85 +- components/radio/Radio.jsx | 74 +- components/radio/RadioButton.jsx | 20 +- components/radio/__tests__/demo.test.js | 4 +- components/radio/__tests__/group.test.js | 158 +- components/radio/__tests__/radio.test.js | 56 +- components/radio/demo/index.vue | 28 +- components/radio/index.js | 25 +- components/rate/__tests__/demo.test.js | 4 +- components/rate/__tests__/index.test.js | 8 +- components/rate/demo/index.vue | 22 +- components/rate/index.jsx | 43 +- components/row/index.js | 10 +- components/select/__tests__/demo.test.js | 4 +- components/select/__tests__/index.test.js | 229 +-- components/select/demo/index.vue | 38 +- components/select/index.jsx | 204 ++- components/skeleton/Avatar.jsx | 26 +- components/skeleton/Paragraph.jsx | 50 +- components/skeleton/Title.jsx | 30 +- components/skeleton/__tests__/demo.test.js | 4 +- components/skeleton/__tests__/index.test.js | 84 +- components/skeleton/demo/index.vue | 20 +- components/skeleton/index.jsx | 127 +- components/slider/__tests__/demo.test.js | 4 +- components/slider/__tests__/index.test.js | 60 +- components/slider/demo/index.vue | 26 +- components/slider/index.jsx | 100 +- components/spin/Spin.jsx | 129 +- components/spin/__tests__/demo.test.js | 4 +- components/spin/__tests__/index.test.js | 74 +- components/spin/demo/index.vue | 24 +- components/spin/index.js | 14 +- components/steps/__tests__/demo.test.js | 4 +- components/steps/demo/index.vue | 28 +- components/steps/index.jsx | 55 +- components/style.js | 110 +- components/switch/__tests__/demo.test.js | 4 +- components/switch/__tests__/index.test.js | 8 +- components/switch/demo/index.vue | 20 +- components/switch/index.jsx | 50 +- components/table/Column.jsx | 4 +- components/table/ColumnGroup.jsx | 5 +- .../table/FilterDropdownMenuWrapper.jsx | 17 +- components/table/SelectionBox.jsx | 72 +- components/table/SelectionCheckboxAll.jsx | 204 ++- components/table/Table.jsx | 1081 +++++++------ .../table/__tests__/SelectionBox.test.js | 84 +- .../table/__tests__/Table.filter.test.js | 524 +++--- .../table/__tests__/Table.pagination.test.js | 287 ++-- .../__tests__/Table.rowSelection.test.js | 743 +++++---- .../table/__tests__/Table.sorter.test.js | 200 ++- components/table/__tests__/Table.test.js | 151 +- components/table/__tests__/demo.test.js | 4 +- components/table/__tests__/empty.test.js | 128 +- components/table/createBodyRow.jsx | 49 +- components/table/createStore.jsx | 10 +- components/table/demo/EditableCell.vue | 14 +- components/table/demo/index.vue | 52 +- components/table/filterDropdown.jsx | 274 ++-- components/table/index.jsx | 124 +- components/table/interface.js | 30 +- components/table/util.js | 47 +- components/tabs/TabBar.jsx | 38 +- components/tabs/__tests__/demo.test.js | 4 +- components/tabs/__tests__/index.test.js | 60 +- components/tabs/demo/index.vue | 34 +- components/tabs/index.js | 30 +- components/tabs/tabs.jsx | 156 +- components/tag/CheckableTag.jsx | 24 +- components/tag/Tag.jsx | 96 +- components/tag/__tests__/demo.test.js | 4 +- components/tag/__tests__/index.test.js | 110 +- components/tag/demo/index.vue | 22 +- components/tag/index.js | 17 +- components/time-picker/__tests__/demo.test.js | 4 +- .../time-picker/__tests__/index.test.js | 30 +- components/time-picker/demo/index.vue | 28 +- components/time-picker/index.jsx | 186 +-- components/time-picker/locale/ar_EG.js | 4 +- components/time-picker/locale/bg_BG.js | 4 +- components/time-picker/locale/ca_ES.js | 4 +- components/time-picker/locale/cs_CZ.js | 4 +- components/time-picker/locale/da_DK.js | 4 +- components/time-picker/locale/de_DE.js | 4 +- components/time-picker/locale/el_GR.js | 4 +- components/time-picker/locale/en_GB.js | 4 +- components/time-picker/locale/en_US.js | 4 +- components/time-picker/locale/es_ES.js | 4 +- components/time-picker/locale/et_EE.js | 4 +- components/time-picker/locale/fa_IR.js | 4 +- components/time-picker/locale/fi_FI.js | 4 +- components/time-picker/locale/fr_BE.js | 6 +- components/time-picker/locale/fr_FR.js | 6 +- components/time-picker/locale/he_IL.js | 4 +- components/time-picker/locale/hu_HU.js | 4 +- components/time-picker/locale/id_ID.js | 4 +- components/time-picker/locale/is_IS.js | 4 +- components/time-picker/locale/it_IT.js | 6 +- components/time-picker/locale/ja_JP.js | 4 +- components/time-picker/locale/ko_KR.js | 4 +- components/time-picker/locale/ku_IQ.js | 4 +- components/time-picker/locale/mn_MN.js | 4 +- components/time-picker/locale/nb_NO.js | 4 +- components/time-picker/locale/nl_BE.js | 4 +- components/time-picker/locale/nl_NL.js | 4 +- components/time-picker/locale/pl_PL.js | 4 +- components/time-picker/locale/pt_BR.js | 4 +- components/time-picker/locale/pt_PT.js | 4 +- components/time-picker/locale/ru_RU.js | 4 +- components/time-picker/locale/sk_SK.js | 4 +- components/time-picker/locale/sl_SI.js | 4 +- components/time-picker/locale/sr_RS.js | 4 +- components/time-picker/locale/sv_SE.js | 4 +- components/time-picker/locale/th_TH.js | 4 +- components/time-picker/locale/tr_TR.js | 4 +- components/time-picker/locale/uk_UA.js | 4 +- components/time-picker/locale/vi_VN.js | 4 +- components/time-picker/locale/zh_CN.js | 4 +- components/time-picker/locale/zh_TW.js | 4 +- components/timeline/Timeline.jsx | 83 +- components/timeline/TimelineItem.jsx | 28 +- components/timeline/__tests__/demo.test.js | 4 +- components/timeline/demo/index.vue | 22 +- components/timeline/index.jsx | 20 +- components/tooltip/Tooltip.jsx | 182 ++- components/tooltip/__tests__/demo.test.js | 4 +- components/tooltip/__tests__/tooltip.test.js | 143 +- components/tooltip/abstractTooltipProps.js | 23 +- components/tooltip/demo/index.vue | 18 +- components/tooltip/index.js | 11 +- components/tooltip/placements.js | 49 +- components/transfer/__tests__/demo.test.js | 4 +- components/transfer/__tests__/index.test.js | 515 +++--- components/transfer/__tests__/list.test.js | 62 +- components/transfer/__tests__/search.test.js | 124 +- components/transfer/demo/index.vue | 18 +- components/transfer/index.jsx | 337 ++-- components/transfer/item.jsx | 53 +- components/transfer/list.jsx | 237 +-- components/transfer/operation.jsx | 31 +- components/transfer/search.jsx | 49 +- components/tree-select/__tests__/demo.test.js | 4 +- .../tree-select/__tests__/index.test.js | 8 +- components/tree-select/demo/index.vue | 20 +- components/tree-select/index.jsx | 157 +- components/tree-select/interface.jsx | 8 +- components/tree/DirectoryTree.jsx | 179 ++- components/tree/Tree.jsx | 128 +- components/tree/__tests__/demo.test.js | 4 +- components/tree/__tests__/util.test.js | 53 +- components/tree/demo/index.vue | 26 +- components/tree/index.jsx | 21 +- components/tree/util.js | 62 +- components/upload/Dragger.jsx | 16 +- components/upload/Upload.jsx | 243 ++- components/upload/UploadList.jsx | 259 +-- components/upload/__tests__/demo.test.js | 4 +- components/upload/__tests__/requests.js | 12 +- components/upload/__tests__/upload.test.js | 288 ++-- .../upload/__tests__/uploadlist.test.js | 296 ++-- components/upload/demo/index.vue | 28 +- components/upload/index.jsx | 18 +- components/upload/interface.jsx | 32 +- components/upload/utils.jsx | 48 +- components/vc-align/Align.jsx | 156 +- components/vc-align/demo/point.vue | 12 +- components/vc-align/demo/simple.vue | 20 +- components/vc-align/index.js | 4 +- components/vc-align/util.js | 36 +- .../vc-calendar/assets/common/Calendar.less | 10 +- .../assets/common/FullCalendar.less | 4 +- .../assets/common/RangeCalendar.less | 13 +- .../vc-calendar/assets/common/index.less | 4 +- components/vc-calendar/assets/index.less | 20 +- .../vc-calendar/assets/index/Calendar.less | 32 +- .../vc-calendar/assets/index/DecadePanel.less | 14 +- .../vc-calendar/assets/index/Input.less | 5 +- .../vc-calendar/assets/index/MonthPanel.less | 13 +- .../vc-calendar/assets/index/Picker.less | 2 +- components/vc-calendar/assets/index/Time.less | 6 +- .../vc-calendar/assets/index/TimePanel.less | 8 +- .../vc-calendar/assets/index/YearPanel.less | 14 +- components/vc-calendar/demo/antd-calendar.vue | 110 +- .../vc-calendar/demo/antd-month-calendar.vue | 68 +- .../vc-calendar/demo/antd-range-calendar.vue | 128 +- components/vc-calendar/demo/full-calendar.vue | 46 +- components/vc-calendar/index.js | 4 +- components/vc-calendar/src/Calendar.jsx | 255 +-- components/vc-calendar/src/FullCalendar.jsx | 127 +- components/vc-calendar/src/MonthCalendar.jsx | 106 +- components/vc-calendar/src/Picker.jsx | 230 +-- components/vc-calendar/src/RangeCalendar.jsx | 708 ++++---- .../src/calendar/CalendarFooter.jsx | 79 +- .../src/calendar/CalendarHeader.jsx | 255 +-- .../vc-calendar/src/calendar/OkButton.jsx | 23 +- .../src/calendar/TimePickerButton.jsx | 27 +- .../vc-calendar/src/calendar/TodayButton.jsx | 30 +- .../vc-calendar/src/date/DateConstants.js | 2 +- components/vc-calendar/src/date/DateInput.jsx | 160 +- components/vc-calendar/src/date/DateTBody.jsx | 247 +-- components/vc-calendar/src/date/DateTHead.jsx | 71 +- components/vc-calendar/src/date/DateTable.jsx | 26 +- .../vc-calendar/src/decade/DecadePanel.jsx | 132 +- .../src/full-calendar/CalendarHeader.jsx | 133 +- components/vc-calendar/src/index.js | 4 +- components/vc-calendar/src/locale/ar_EG.js | 2 +- components/vc-calendar/src/locale/bg_BG.js | 2 +- components/vc-calendar/src/locale/ca_ES.js | 2 +- components/vc-calendar/src/locale/cs_CZ.js | 2 +- components/vc-calendar/src/locale/da_DK.js | 2 +- components/vc-calendar/src/locale/de_DE.js | 2 +- components/vc-calendar/src/locale/el_GR.js | 2 +- components/vc-calendar/src/locale/en_GB.js | 2 +- components/vc-calendar/src/locale/en_US.js | 2 +- components/vc-calendar/src/locale/es_ES.js | 2 +- components/vc-calendar/src/locale/et_EE.js | 2 +- components/vc-calendar/src/locale/fa_IR.js | 2 +- components/vc-calendar/src/locale/fi_FI.js | 2 +- components/vc-calendar/src/locale/fr_BE.js | 10 +- components/vc-calendar/src/locale/fr_FR.js | 8 +- components/vc-calendar/src/locale/he_IL.js | 2 +- components/vc-calendar/src/locale/hu_HU.js | 2 +- components/vc-calendar/src/locale/id_ID.js | 2 +- components/vc-calendar/src/locale/is_IS.js | 2 +- components/vc-calendar/src/locale/it_IT.js | 10 +- components/vc-calendar/src/locale/ja_JP.js | 2 +- components/vc-calendar/src/locale/ko_KR.js | 2 +- components/vc-calendar/src/locale/ku_IQ.js | 2 +- components/vc-calendar/src/locale/mm_MM.js | 2 +- components/vc-calendar/src/locale/mn_MN.js | 2 +- components/vc-calendar/src/locale/nb_NO.js | 2 +- components/vc-calendar/src/locale/nl_BE.js | 2 +- components/vc-calendar/src/locale/nl_NL.js | 2 +- components/vc-calendar/src/locale/pl_PL.js | 2 +- components/vc-calendar/src/locale/pt_BR.js | 2 +- components/vc-calendar/src/locale/pt_PT.js | 2 +- components/vc-calendar/src/locale/ru_RU.js | 2 +- components/vc-calendar/src/locale/sk_SK.js | 2 +- components/vc-calendar/src/locale/sl_SI.js | 2 +- components/vc-calendar/src/locale/sr_RS.js | 2 +- components/vc-calendar/src/locale/sv_SE.js | 2 +- components/vc-calendar/src/locale/th_TH.js | 2 +- components/vc-calendar/src/locale/tr_TR.js | 2 +- components/vc-calendar/src/locale/ug_CN.js | 2 +- components/vc-calendar/src/locale/uk_UA.js | 2 +- components/vc-calendar/src/locale/vi_VN.js | 2 +- components/vc-calendar/src/locale/zh_CN.js | 2 +- components/vc-calendar/src/locale/zh_TW.js | 2 +- .../vc-calendar/src/mixin/CalendarMixin.js | 110 +- .../vc-calendar/src/mixin/CommonMixin.js | 19 +- .../vc-calendar/src/month/MonthPanel.jsx | 81 +- .../vc-calendar/src/month/MonthTable.jsx | 139 +- .../vc-calendar/src/picker/placements.js | 8 +- .../src/range-calendar/CalendarPart.jsx | 97 +- components/vc-calendar/src/util/index.js | 108 +- components/vc-calendar/src/util/toTime.js | 16 +- components/vc-calendar/src/year/YearPanel.jsx | 128 +- components/vc-cascader/Cascader.jsx | 320 ++-- components/vc-cascader/Menus.jsx | 164 +- components/vc-cascader/assets/index.less | 9 +- components/vc-cascader/demo/animation.vue | 16 +- .../vc-cascader/demo/custom-field-name.vue | 16 +- components/vc-cascader/index.js | 4 +- components/vc-checkbox/assets/index.less | 10 +- components/vc-checkbox/demo/simple.js | 45 +- components/vc-checkbox/index.js | 2 +- components/vc-checkbox/src/Checkbox.jsx | 134 +- components/vc-checkbox/src/index.js | 5 +- components/vc-collapse/index.js | 12 +- components/vc-collapse/src/Collapse.jsx | 111 +- components/vc-collapse/src/Panel.jsx | 49 +- components/vc-collapse/src/PanelContent.jsx | 37 +- components/vc-collapse/src/commonProps.js | 24 +- .../vc-collapse/src/openAnimationFactory.js | 40 +- components/vc-dialog/Dialog.jsx | 414 ++--- components/vc-dialog/DialogWrap.jsx | 66 +- components/vc-dialog/IDialogPropTypes.js | 8 +- components/vc-dialog/LazyRenderBox.jsx | 16 +- components/vc-dialog/assets/bootstrap.less | 4 +- .../vc-dialog/assets/bootstrap/Dialog.less | 14 +- .../vc-dialog/assets/bootstrap/effect.less | 5 +- .../vc-dialog/assets/bootstrap/variables.less | 800 +++++---- components/vc-dialog/assets/index.less | 4 +- components/vc-dialog/assets/index/Dialog.less | 11 +- components/vc-dialog/assets/index/Mask.less | 6 +- components/vc-dialog/demo/ant-design.vue | 36 +- components/vc-dialog/index.js | 4 +- components/vc-drawer/assets/index.less | 27 +- components/vc-drawer/demo/change-remove.jsx | 145 +- components/vc-drawer/demo/change.jsx | 121 +- components/vc-drawer/demo/getContainer.jsx | 81 +- components/vc-drawer/demo/level.jsx | 109 +- components/vc-drawer/demo/multiple.jsx | 70 +- components/vc-drawer/demo/placement.jsx | 127 +- components/vc-drawer/src/Drawer.js | 599 +++---- components/vc-drawer/src/drawerProps.js | 11 +- components/vc-drawer/src/index.js | 4 +- components/vc-drawer/src/utils.js | 48 +- components/vc-dropdown/src/Dropdown.jsx | 120 +- components/vc-dropdown/src/index.js | 4 +- components/vc-dropdown/src/placements.js | 8 +- components/vc-form/demo/async-init.js | 165 +- components/vc-form/demo/dynamic-fields.js | 180 ++- components/vc-form/demo/dynamic.js | 191 ++- components/vc-form/demo/file-input.js | 90 +- components/vc-form/demo/getFieldDecorator.js | 50 +- components/vc-form/demo/input-array.jsx | 77 +- components/vc-form/demo/modal.js | 80 +- components/vc-form/demo/nested-field.js | 181 +-- components/vc-form/demo/normalize.js | 190 +-- components/vc-form/demo/overview.js | 274 ++-- components/vc-form/demo/parallel-form.js | 62 +- components/vc-form/demo/promise-validate.js | 33 +- components/vc-form/demo/start-end-date.js | 96 +- components/vc-form/demo/styles.js | 4 +- components/vc-form/demo/suggest.js | 128 +- components/vc-form/demo/validateFirst.js | 191 +-- components/vc-form/demo/validateTrigger.js | 163 +- components/vc-form/index.js | 4 +- components/vc-form/src/createBaseForm.jsx | 657 ++++---- components/vc-form/src/createDOMForm.jsx | 103 +- components/vc-form/src/createFieldsStore.jsx | 306 ++-- components/vc-form/src/createForm.jsx | 16 +- components/vc-form/src/createFormField.jsx | 14 +- components/vc-form/src/index.jsx | 14 +- components/vc-form/src/propTypes.js | 6 +- components/vc-form/src/utils.js | 149 +- components/vc-input-number/assets/index.less | 20 +- .../demo/combination-key-format.jsx | 49 +- components/vc-input-number/demo/custom.jsx | 36 +- components/vc-input-number/demo/decimal.jsx | 34 +- components/vc-input-number/demo/formatter.jsx | 40 +- components/vc-input-number/demo/index.vue | 18 +- components/vc-input-number/demo/precision.jsx | 40 +- .../vc-input-number/demo/simple-use-touch.jsx | 34 +- components/vc-input-number/demo/simple.jsx | 34 +- .../vc-input-number/demo/small-step.jsx | 32 +- .../vc-input-number/src/InputHandler.js | 24 +- components/vc-input-number/src/index.js | 670 ++++---- components/vc-lazy-load/demo/index.jsx | 40 +- components/vc-lazy-load/index.js | 5 +- components/vc-lazy-load/src/LazyLoad.jsx | 146 +- .../src/utils/getElementPosition.js | 12 +- .../vc-lazy-load/src/utils/inViewport.js | 39 +- .../vc-lazy-load/src/utils/parentScroll.js | 34 +- components/vc-m-feedback/demo/simple.jsx | 25 +- components/vc-m-feedback/demo/simple.less | 2 +- components/vc-m-feedback/index.js | 4 +- components/vc-m-feedback/src/PropTypes.jsx | 4 +- .../vc-m-feedback/src/TouchFeedback.jsx | 101 +- components/vc-menu/DOMWrap.jsx | 258 ++- components/vc-menu/Divider.jsx | 10 +- components/vc-menu/Menu.jsx | 154 +- components/vc-menu/MenuItem.jsx | 144 +- components/vc-menu/MenuItemGroup.jsx | 37 +- components/vc-menu/SubMenu.jsx | 391 ++--- components/vc-menu/SubPopupMenu.jsx | 402 ++--- components/vc-menu/assets/index.less | 60 +- components/vc-menu/commonPropsType.js | 20 +- components/vc-menu/index.js | 22 +- components/vc-menu/placements.js | 6 +- components/vc-menu/util.js | 80 +- components/vc-notification/Notice.jsx | 91 +- components/vc-notification/Notification.jsx | 168 +- components/vc-notification/assets/index.less | 2 +- components/vc-notification/demo/simple.jsx | 105 +- components/vc-notification/index.js | 4 +- components/vc-pagination/KeyCode.js | 2 +- components/vc-pagination/Options.jsx | 95 +- components/vc-pagination/Pager.jsx | 40 +- components/vc-pagination/Pagination.jsx | 419 +++-- components/vc-pagination/assets/index.less | 58 +- components/vc-pagination/demo/default.vue | 14 +- components/vc-pagination/demo/itemRender.vue | 20 +- components/vc-pagination/demo/jumper.vue | 22 +- .../vc-pagination/demo/jumperWithGoButton.vue | 22 +- components/vc-pagination/demo/lessPages.vue | 14 +- components/vc-pagination/demo/more.vue | 10 +- components/vc-pagination/demo/showTitle.vue | 14 +- components/vc-pagination/demo/showTotal.vue | 10 +- components/vc-pagination/demo/simple.vue | 10 +- components/vc-pagination/demo/sizer.vue | 18 +- components/vc-pagination/demo/stupid.vue | 10 +- components/vc-pagination/demo/styles.vue | 10 +- components/vc-pagination/index.js | 2 +- components/vc-pagination/locale/ar_EG.js | 2 +- components/vc-pagination/locale/bg_BG.js | 2 +- components/vc-pagination/locale/ca_ES.js | 2 +- components/vc-pagination/locale/cs_CZ.js | 2 +- components/vc-pagination/locale/da_DK.js | 2 +- components/vc-pagination/locale/de_DE.js | 2 +- components/vc-pagination/locale/el_GR.js | 2 +- components/vc-pagination/locale/en_GB.js | 2 +- components/vc-pagination/locale/en_US.js | 2 +- components/vc-pagination/locale/es_ES.js | 2 +- components/vc-pagination/locale/et_EE.js | 2 +- components/vc-pagination/locale/fa_IR.js | 2 +- components/vc-pagination/locale/fi_FI.js | 2 +- components/vc-pagination/locale/fr_BE.js | 2 +- components/vc-pagination/locale/fr_FR.js | 2 +- components/vc-pagination/locale/he_IL.js | 2 +- components/vc-pagination/locale/hi_IN.js | 2 +- components/vc-pagination/locale/hu_HU.js | 2 +- components/vc-pagination/locale/id_ID.js | 2 +- components/vc-pagination/locale/is_IS.js | 2 +- components/vc-pagination/locale/it_IT.js | 2 +- components/vc-pagination/locale/ja_JP.js | 2 +- components/vc-pagination/locale/kn_IN.js | 2 +- components/vc-pagination/locale/ko_KR.js | 2 +- components/vc-pagination/locale/ku_IQ.js | 2 +- components/vc-pagination/locale/mm_MM.js | 2 +- components/vc-pagination/locale/mn_MN.js | 2 +- components/vc-pagination/locale/nb_NO.js | 2 +- components/vc-pagination/locale/nl_BE.js | 10 +- components/vc-pagination/locale/nl_NL.js | 10 +- components/vc-pagination/locale/pl_PL.js | 2 +- components/vc-pagination/locale/pt_BR.js | 2 +- components/vc-pagination/locale/pt_PT.js | 2 +- components/vc-pagination/locale/ro_RO.js | 2 +- components/vc-pagination/locale/ru_RU.js | 2 +- components/vc-pagination/locale/sk_SK.js | 2 +- components/vc-pagination/locale/sl_SI.js | 2 +- components/vc-pagination/locale/sr_RS.js | 2 +- components/vc-pagination/locale/sv_SE.js | 2 +- components/vc-pagination/locale/th_TH.js | 2 +- components/vc-pagination/locale/tr_TR.js | 2 +- components/vc-pagination/locale/ug_CN.js | 2 +- components/vc-pagination/locale/uk_UA.js | 2 +- components/vc-pagination/locale/vi_VN.js | 2 +- components/vc-pagination/locale/zh_CN.js | 2 +- components/vc-pagination/locale/zh_TW.js | 2 +- components/vc-progress/demo/fast-progress.jsx | 48 +- components/vc-progress/demo/gap.jsx | 58 +- components/vc-progress/demo/simple.jsx | 34 +- components/vc-progress/index.js | 9 +- components/vc-progress/src/Circle.js | 118 +- components/vc-progress/src/Line.js | 55 +- components/vc-progress/src/enhancer.js | 22 +- components/vc-progress/src/index.js | 11 +- components/vc-progress/src/types.js | 6 +- components/vc-rate/assets/index.less | 23 +- components/vc-rate/demo/simple.jsx | 55 +- components/vc-rate/index.js | 4 +- components/vc-rate/src/Rate.jsx | 177 +- components/vc-rate/src/Star.jsx | 58 +- components/vc-rate/src/index.js | 4 +- components/vc-rate/src/util.js | 50 +- components/vc-select/DropdownMenu.jsx | 174 +- components/vc-select/OptGroup.jsx | 16 +- components/vc-select/Option.jsx | 21 +- components/vc-select/PropTypes.js | 4 +- components/vc-select/Select.jsx | 1432 ++++++++--------- components/vc-select/SelectTrigger.jsx | 163 +- components/vc-select/demo/combobox.vue | 20 +- components/vc-select/demo/email.vue | 26 +- components/vc-select/demo/force-suggest.vue | 30 +- components/vc-select/demo/mul-suggest.vue | 26 +- components/vc-select/demo/mul-tag-suggest.vue | 28 +- .../vc-select/demo/multiple-readonly.vue | 28 +- components/vc-select/demo/multiple.vue | 26 +- components/vc-select/demo/optgroup.vue | 10 +- .../vc-select/demo/optionFilterProp.vue | 10 +- components/vc-select/demo/optionLabelProp.vue | 12 +- components/vc-select/demo/single.vue | 32 +- components/vc-select/demo/suggest.vue | 34 +- components/vc-select/demo/tags.vue | 26 +- components/vc-select/demo/tbFetchSuggest.js | 40 +- components/vc-select/index.js | 20 +- components/vc-select/util.js | 204 +-- components/vc-slick/assets/docs.less | 21 +- components/vc-slick/assets/index.less | 6 +- components/vc-slick/assets/slick-theme.less | 234 ++- components/vc-slick/assets/slick.less | 149 +- components/vc-slick/demo/AdaptiveHeight.jsx | 12 +- components/vc-slick/demo/AppendDots.jsx | 16 +- components/vc-slick/demo/AsNavFor.jsx | 27 +- components/vc-slick/demo/AutoPlay.jsx | 12 +- components/vc-slick/demo/AutoPlayMethods.jsx | 24 +- components/vc-slick/demo/CenterMode.jsx | 12 +- components/vc-slick/demo/CustomArrows.jsx | 32 +- components/vc-slick/demo/CustomPaging.jsx | 20 +- components/vc-slick/demo/CustomSlides.jsx | 18 +- components/vc-slick/demo/DynamicSlides.jsx | 26 +- components/vc-slick/demo/Fade.jsx | 18 +- components/vc-slick/demo/FocusOnSelect.jsx | 12 +- components/vc-slick/demo/LazyLoad.jsx | 18 +- components/vc-slick/demo/MultipleItems.jsx | 12 +- components/vc-slick/demo/MultipleRows.jsx | 12 +- components/vc-slick/demo/PauseOnHover.jsx | 12 +- .../vc-slick/demo/PreviousNextMethods.jsx | 24 +- components/vc-slick/demo/Resizable.jsx | 46 +- components/vc-slick/demo/Responsive.jsx | 12 +- components/vc-slick/demo/Rtl.jsx | 12 +- components/vc-slick/demo/SimpleSlider.jsx | 14 +- components/vc-slick/demo/SlickGoTo.jsx | 32 +- components/vc-slick/demo/SlideChangeHooks.jsx | 24 +- components/vc-slick/demo/SwipeToSlide.jsx | 18 +- components/vc-slick/demo/UnevenSetsFinite.jsx | 12 +- .../vc-slick/demo/UnevenSetsInfinite.jsx | 12 +- components/vc-slick/demo/VariableWidth.jsx | 12 +- components/vc-slick/demo/VerticalMode.jsx | 20 +- .../vc-slick/demo/VerticalSwipeToSlide.jsx | 20 +- components/vc-slick/demo/config.js | 2 +- components/vc-slick/demo/imglist.js | 10 +- components/vc-slick/demo/index.jsx | 66 +- components/vc-slick/src/arrows.js | 144 +- components/vc-slick/src/default-props.js | 6 +- components/vc-slick/src/dots.js | 79 +- components/vc-slick/src/index.js | 4 +- components/vc-slick/src/initial-state.js | 4 +- components/vc-slick/src/inner-slider.js | 709 ++++---- components/vc-slick/src/slider.js | 213 ++- components/vc-slick/src/track.js | 201 ++- .../vc-slick/src/utils/innerSliderUtils.js | 702 ++++---- components/vc-slider/assets/index.less | 27 +- components/vc-slider/demo/handle.jsx | 47 +- components/vc-slider/demo/marks.jsx | 18 +- components/vc-slider/demo/range.jsx | 142 +- components/vc-slider/demo/slider.jsx | 157 +- components/vc-slider/demo/vertical.jsx | 53 +- components/vc-slider/index.js | 10 +- components/vc-slider/src/Handle.jsx | 91 +- components/vc-slider/src/Range.jsx | 415 ++--- components/vc-slider/src/Slider.jsx | 200 +-- components/vc-slider/src/common/Marks.jsx | 104 +- components/vc-slider/src/common/Steps.jsx | 63 +- components/vc-slider/src/common/Track.jsx | 30 +- .../vc-slider/src/common/createSlider.jsx | 266 +-- .../vc-slider/src/createSliderWithTooltip.jsx | 67 +- components/vc-slider/src/index.js | 18 +- components/vc-slider/src/utils.js | 127 +- components/vc-steps/Step.jsx | 99 +- components/vc-steps/Steps.jsx | 178 +- components/vc-steps/assets/iconfont.less | 544 +++++-- components/vc-steps/assets/index.less | 12 +- components/vc-steps/assets/small.less | 6 +- components/vc-steps/assets/variables.less | 6 +- components/vc-steps/demo/alternativeLabel.vue | 14 +- components/vc-steps/demo/composable.vue | 14 +- components/vc-steps/demo/custom-svg-icon.jsx | 63 +- components/vc-steps/demo/customIcon.vue | 12 +- components/vc-steps/demo/dynamic.vue | 14 +- components/vc-steps/demo/errorStep.vue | 14 +- components/vc-steps/demo/nextStep.vue | 32 +- components/vc-steps/demo/progressDot.vue | 14 +- components/vc-steps/demo/simple.vue | 14 +- components/vc-steps/demo/smallSize.vue | 12 +- components/vc-steps/demo/vertical.vue | 14 +- components/vc-steps/demo/verticalSmall.vue | 14 +- components/vc-steps/index.js | 10 +- components/vc-switch/PropTypes.js | 4 +- components/vc-switch/Switch.jsx | 90 +- components/vc-switch/assets/index.less | 4 +- components/vc-switch/demo/simple.vue | 12 +- components/vc-switch/index.js | 4 +- components/vc-table/assets/animation.less | 13 +- components/vc-table/assets/bordered.less | 3 +- components/vc-table/assets/index.less | 20 +- components/vc-table/demo/childrenIndent.js | 175 +- components/vc-table/demo/className.js | 37 +- components/vc-table/demo/colspan-rowspan.js | 194 ++- components/vc-table/demo/column-resize.js | 54 +- components/vc-table/demo/dropdown.js | 81 +- components/vc-table/demo/expandIcon.js | 35 +- components/vc-table/demo/expandedRowRender.js | 73 +- .../vc-table/demo/fixedColumns-auto-height.js | 50 +- components/vc-table/demo/fixedColumns.js | 32 +- .../vc-table/demo/fixedColumnsAndHeader.js | 21 +- .../fixedColumnsAndHeaderSyncRowHeight.js | 14 +- components/vc-table/demo/grouping-columns.js | 61 +- components/vc-table/demo/jsx.js | 51 +- components/vc-table/demo/key.js | 52 +- components/vc-table/demo/nested.js | 61 +- components/vc-table/demo/no-data.js | 22 +- components/vc-table/demo/rowAndCellClick.js | 183 ++- components/vc-table/demo/scrollX.js | 15 +- components/vc-table/demo/scrollXY.js | 15 +- components/vc-table/demo/scrollY.js | 35 +- components/vc-table/demo/styled-components.js | 27 +- components/vc-table/demo/subTable.js | 39 +- components/vc-table/demo/title-and-footer.js | 22 +- components/vc-table/index.js | 82 +- components/vc-table/src/BaseTable.jsx | 179 +-- components/vc-table/src/BodyTable.jsx | 101 +- components/vc-table/src/ColGroup.jsx | 41 +- components/vc-table/src/Column.jsx | 15 +- components/vc-table/src/ColumnGroup.jsx | 4 +- components/vc-table/src/ColumnManager.jsx | 131 +- components/vc-table/src/ExpandIcon.jsx | 22 +- components/vc-table/src/ExpandableRow.jsx | 94 +- components/vc-table/src/ExpandableTable.jsx | 180 ++- components/vc-table/src/HeadTable.jsx | 54 +- components/vc-table/src/Table.jsx | 575 +++---- components/vc-table/src/TableCell.jsx | 75 +- components/vc-table/src/TableHeader.jsx | 77 +- components/vc-table/src/TableHeaderRow.jsx | 87 +- components/vc-table/src/TableRow.jsx | 311 ++-- components/vc-table/src/utils.js | 96 +- components/vc-tabs/src/InkTabBar.jsx | 35 +- components/vc-tabs/src/InkTabBarNode.jsx | 132 +- components/vc-tabs/src/KeyCode.js | 2 +- components/vc-tabs/src/SaveRef.jsx | 24 +- .../vc-tabs/src/ScrollableInkTabBar.jsx | 52 +- components/vc-tabs/src/ScrollableTabBar.jsx | 34 +- .../vc-tabs/src/ScrollableTabBarNode.jsx | 334 ++-- components/vc-tabs/src/Sentinel.jsx | 42 +- components/vc-tabs/src/TabBar.jsx | 32 +- components/vc-tabs/src/TabBarRootNode.jsx | 54 +- components/vc-tabs/src/TabBarTabsNode.jsx | 98 +- components/vc-tabs/src/TabContent.jsx | 86 +- components/vc-tabs/src/TabPane.jsx | 65 +- components/vc-tabs/src/Tabs.jsx | 214 ++- components/vc-tabs/src/index.js | 16 +- components/vc-tabs/src/utils.js | 129 +- components/vc-time-picker/Combobox.jsx | 128 +- components/vc-time-picker/Header.jsx | 168 +- components/vc-time-picker/Panel.jsx | 139 +- components/vc-time-picker/Select.jsx | 136 +- components/vc-time-picker/TimePicker.jsx | 355 ++-- components/vc-time-picker/assets/index.less | 8 +- .../vc-time-picker/assets/index/Header.less | 2 +- .../vc-time-picker/assets/index/Picker.less | 4 +- components/vc-time-picker/demo/all.vue | 52 +- components/vc-time-picker/index.js | 2 +- components/vc-time-picker/placements.js | 8 +- components/vc-tooltip/Content.jsx | 18 +- components/vc-tooltip/Tooltip.jsx | 77 +- .../vc-tooltip/assets/boostrap/anim.less | 11 +- components/vc-tooltip/assets/bootstrap.less | 27 +- .../vc-tooltip/assets/bootstrap_white.less | 22 +- components/vc-tooltip/index.js | 4 +- components/vc-tooltip/placements.js | 8 +- components/vc-tree-select/assets/index.less | 4 +- components/vc-tree-select/assets/select.less | 43 +- components/vc-tree-select/assets/tree.less | 20 +- components/vc-tree-select/demo/basic.jsx | 348 ++-- .../vc-tree-select/demo/big-data-generator.js | 82 +- components/vc-tree-select/demo/big-data.js | 104 +- components/vc-tree-select/demo/controlled.jsx | 63 +- .../vc-tree-select/demo/custom-icons.jsx | 91 +- components/vc-tree-select/demo/demo.less | 2 +- components/vc-tree-select/demo/disable.js | 91 +- components/vc-tree-select/demo/dynamic.js | 38 +- components/vc-tree-select/demo/filter.js | 58 +- components/vc-tree-select/demo/form.js | 194 +-- components/vc-tree-select/demo/styles.js | 4 +- components/vc-tree-select/demo/util.js | 155 +- components/vc-tree-select/index.js | 12 +- .../vc-tree-select/src/Base/BasePopup.jsx | 188 ++- .../vc-tree-select/src/Base/BaseSelector.jsx | 179 ++- .../src/Popup/MultiplePopup.jsx | 4 +- .../vc-tree-select/src/Popup/SinglePopup.jsx | 50 +- components/vc-tree-select/src/SearchInput.jsx | 119 +- components/vc-tree-select/src/Select.jsx | 990 ++++++------ components/vc-tree-select/src/SelectNode.jsx | 38 +- .../vc-tree-select/src/SelectTrigger.jsx | 82 +- .../Selector/MultipleSelector/Selection.jsx | 54 +- .../src/Selector/MultipleSelector/index.jsx | 180 ++- .../src/Selector/SingleSelector.jsx | 75 +- components/vc-tree-select/src/index.js | 10 +- components/vc-tree-select/src/propTypes.js | 44 +- components/vc-tree-select/src/strategies.js | 6 +- components/vc-tree-select/src/util.js | 353 ++-- components/vc-tree/assets/index.less | 16 +- components/vc-tree/demo/animation.vue | 32 +- components/vc-tree/demo/basic-controlled.vue | 60 +- components/vc-tree/demo/basic.jsx | 128 +- components/vc-tree/demo/basic.less | 2 +- components/vc-tree/demo/contextmenu.vue | 22 +- components/vc-tree/demo/draggable.less | 3 +- components/vc-tree/demo/draggable.vue | 84 +- components/vc-tree/demo/util.js | 185 +-- components/vc-tree/index.js | 4 +- components/vc-tree/src/Tree.jsx | 648 ++++---- components/vc-tree/src/TreeNode.jsx | 526 +++--- components/vc-tree/src/index.js | 12 +- components/vc-tree/src/util.js | 349 ++-- components/vc-trigger/LazyRenderBox.jsx | 24 +- components/vc-trigger/Popup.jsx | 295 ++-- components/vc-trigger/PopupInner.jsx | 18 +- components/vc-trigger/Trigger.jsx | 616 +++---- components/vc-trigger/assets/index.less | 8 +- components/vc-trigger/assets/mask.less | 6 +- components/vc-trigger/demo/nested.vue | 14 +- components/vc-trigger/demo/point.less | 2 +- components/vc-trigger/demo/point.vue | 22 +- components/vc-trigger/demo/simple.vue | 62 +- components/vc-trigger/index.js | 4 +- components/vc-trigger/utils.js | 23 +- components/vc-upload/demo/asyncAction.jsx | 34 +- components/vc-upload/demo/beforeUpload.jsx | 42 +- components/vc-upload/demo/customRequest.js | 54 +- components/vc-upload/demo/directoryUpload.js | 34 +- components/vc-upload/demo/drag.jsx | 34 +- components/vc-upload/demo/index.vue | 16 +- components/vc-upload/demo/simple.jsx | 62 +- components/vc-upload/index.js | 4 +- components/vc-upload/src/AjaxUploader.jsx | 229 ++- components/vc-upload/src/IframeUploader.jsx | 278 ++-- components/vc-upload/src/Upload.jsx | 70 +- components/vc-upload/src/attr-accept.js | 26 +- components/vc-upload/src/index.js | 4 +- components/vc-upload/src/request.js | 76 +- components/vc-upload/src/traverseFileTree.js | 24 +- components/vc-upload/src/uid.js | 8 +- components/version/index.js | 4 +- index-with-locales.js | 16 +- index.js | 26 +- package.json | 378 ++--- postcss.config.js | 6 +- scripts/gulpfile.js | 127 +- scripts/prepub.js | 18 +- scripts/prettier.js | 84 + scripts/run.js | 26 +- scripts/syncStyleFromAntd.js | 53 +- site/components.js | 127 +- site/components/IconSet/CopyableIcon.vue | 12 +- site/components/IconSet/index.vue | 12 +- site/components/api.vue | 6 +- site/components/demoBox.vue | 38 +- site/components/demoContainer.vue | 42 +- site/components/footer.vue | 6 +- site/components/header.vue | 32 +- site/components/iframe.vue | 6 +- site/components/layout.vue | 198 +-- site/components/md.vue | 28 +- site/components/sponsors.vue | 2 +- site/demo.js | 2 +- site/demoRoutes.js | 2 +- site/dev.js | 56 +- site/index.js | 64 +- site/index.less | 28 +- site/routes.js | 44 +- site/theme/en-US.js | 19 +- site/theme/static/colors.less | 10 +- site/theme/static/common.less | 8 +- site/theme/static/demo.less | 34 +- site/theme/static/docsearch.less | 2 +- site/theme/static/highlight.less | 62 +- site/theme/static/home.less | 4 +- site/theme/static/icons.less | 10 +- site/theme/static/markdown.less | 84 +- site/theme/static/mock-browser.less | 2 +- site/theme/static/nprogress.less | 8 +- site/theme/static/page-nav.less | 3 +- site/theme/static/preview-img.less | 2 +- site/theme/static/resource.less | 5 +- site/theme/static/responsive.less | 14 +- site/theme/static/toc.less | 2 +- site/theme/template/IconDisplay/Category.jsx | 48 +- .../template/IconDisplay/CopyableIcon.vue | 8 +- site/theme/template/IconDisplay/fields.js | 415 ++++- site/theme/template/IconDisplay/index.jsx | 171 +- .../theme/template/IconDisplay/themeIcons.jsx | 57 +- site/theme/zh-CN.js | 8 +- site/util.js | 4 +- tests/index.test.js | 18 +- tests/setup.js | 57 +- tests/shared/demoTest.js | 50 +- tests/shared/focusTest.js | 87 +- tests/utils.js | 32 +- types/alert.d.ts | 2 +- types/anchor/anchor-link.d.ts | 2 +- types/anchor/anchor.d.ts | 2 +- types/ant-design-vue.d.ts | 112 +- types/auto-complete.d.ts | 6 +- types/avatar.d.ts | 4 +- types/back-top.d.ts | 26 +- types/badge.d.ts | 2 +- types/breadcrumb.d.ts | 9 +- types/button/button-group.d.ts | 4 +- types/button/button.d.ts | 12 +- types/calendar.d.ts | 4 +- types/card.d.ts | 2 +- types/carousel.d.ts | 2 +- types/cascader.d.ts | 13 +- types/checkbox/checkbox-group.d.ts | 5 +- types/checkbox/checkbox.d.ts | 4 +- types/collapse/collapse-panel.d.ts | 2 +- types/collapse/collapse.d.ts | 4 +- types/component.d.ts | 2 +- types/date-picker/common.d.ts | 6 +- types/date-picker/date-picker.d.ts | 10 +- types/date-picker/month-picker.d.ts | 4 +- types/date-picker/range-picker.d.ts | 6 +- types/date-picker/week-picker.d.ts | 4 +- types/divider.d.ts | 4 +- types/drawer.d.ts | 2 +- types/dropdown/dropdown-button.d.ts | 18 +- types/dropdown/dropdown.d.ts | 16 +- types/form/form-item.d.ts | 6 +- types/form/form.d.ts | 14 +- types/grid/col.d.ts | 2 +- types/grid/row.d.ts | 6 +- types/icon.d.ts | 2 +- types/index.d.ts | 4 +- types/input-number.d.ts | 2 +- types/input/input-group.d.ts | 4 +- types/input/input-search.d.ts | 2 +- types/input/input.d.ts | 10 +- types/input/textarea.d.ts | 2 +- types/layout/layout-sider.d.ts | 6 +- types/layout/layout.d.ts | 4 +- types/list/list-item.d.ts | 4 +- types/list/list.d.ts | 12 +- types/menu/menu-item-group.d.ts | 4 +- types/menu/menu-item.d.ts | 2 +- types/menu/menu.d.ts | 19 +- types/menu/sub-menu.d.ts | 4 +- types/message.d.ts | 5 +- types/modal.d.ts | 10 +- types/notification.d.ts | 4 +- types/pagination.d.ts | 8 +- types/popconfirm.d.ts | 4 +- types/popover.d.ts | 2 +- types/progress.d.ts | 8 +- types/radio/radio-button.d.ts | 4 +- types/radio/radio-group.d.ts | 6 +- types/radio/radio.d.ts | 6 +- types/select/option-group.d.ts | 2 +- types/select/option.d.ts | 2 +- types/select/select.d.ts | 12 +- types/skeleton.d.ts | 4 +- types/slider.d.ts | 8 +- types/spin.d.ts | 2 +- types/steps/step.d.ts | 4 +- types/steps/steps.d.ts | 14 +- types/switch.d.ts | 2 +- types/table/column-group.d.ts | 2 +- types/table/column.d.ts | 14 +- types/table/table.d.ts | 47 +- types/tabs/tab-pane.d.ts | 2 +- types/tabs/tabs.d.ts | 10 +- types/tag/checkable-tag.d.ts | 2 +- types/tag/tag.d.ts | 4 +- types/time-picker.d.ts | 4 +- types/timeline/timeline-item.d.ts | 2 +- types/timeline/timeline.d.ts | 6 +- types/tootip/common.d.ts | 28 +- types/tootip/tooltip.d.ts | 4 +- types/tree-select.d.ts | 8 +- types/tree/dictionary-tree.d.ts | 4 +- types/tree/tree.d.ts | 6 +- types/upload.d.ts | 2 +- webpack.base.config.js | 161 +- webpack.build.config.js | 38 +- webpack.config.js | 23 +- webpack.site.config.js | 25 +- 1264 files changed, 38265 insertions(+), 36569 deletions(-) create mode 100644 .prettierignore create mode 100644 .prettierrc create mode 100644 scripts/prettier.js diff --git a/.eslintignore b/.eslintignore index 0c337a6d9..d7bf0786f 100644 --- a/.eslintignore +++ b/.eslintignore @@ -3,3 +3,7 @@ node_modules/ **/style/ *.html /components/test/* +es/ +lib/ +site-dist/ +dist/ diff --git a/.eslintrc b/.eslintrc index d83133fcf..85a29000c 100644 --- a/.eslintrc +++ b/.eslintrc @@ -7,12 +7,13 @@ "es6": true }, "parser": "babel-eslint", - "extends": ["plugin:vue-libs/recommended"], + "extends": ["plugin:vue-libs/recommended", "prettier"], "rules": { "comma-dangle": [2, "always-multiline"], "no-var": "error", "no-unused-vars": "warn", "camelcase": "off", - "no-extra-boolean-cast": "off" + "no-extra-boolean-cast": "off", + "semi": ["error", "always"] } -} +} \ No newline at end of file diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..35c5c6de0 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,9 @@ +**/*.md +**/*.svg +**/*.ejs +**/*.html +package.json +es/** +lib/** +site-dist/** +dist/** \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..9f5ab919f --- /dev/null +++ b/.prettierrc @@ -0,0 +1,19 @@ +{ + "singleQuote": true, + "trailingComma": "all", + "printWidth": 100, + "overrides": [ + { + "files": ".prettierrc", + "options": { + "parser": "json" + } + }, + { + "files": ".stylelintrc", + "options": { + "parser": "json" + } + } + ] +} diff --git a/.stylelintrc b/.stylelintrc index 74608186c..9d422fb7c 100644 --- a/.stylelintrc +++ b/.stylelintrc @@ -1,6 +1,5 @@ { - "extends": "stylelint-config-standard", - "ignoreFiles": "./components/**", + "extends": ["stylelint-config-standard", "stylelint-config-prettier"], "rules": { "comment-empty-line-before": null, "declaration-empty-line-before": null, diff --git a/antd-tools/cli/index.js b/antd-tools/cli/index.js index 61d130361..6ef2ab5b2 100644 --- a/antd-tools/cli/index.js +++ b/antd-tools/cli/index.js @@ -1,27 +1,27 @@ #!/usr/bin/env node -'use strict' +'use strict'; -require('colorful').colorful() +require('colorful').colorful(); -const program = require('commander') -const packageInfo = require('../../package.json') +const program = require('commander'); +const packageInfo = require('../../package.json'); program .version(packageInfo.version) .command('run [name]', 'run specified task') - .parse(process.argv) + .parse(process.argv); // https://github.com/tj/commander.js/pull/260 -const proc = program.runningCommand +const proc = program.runningCommand; if (proc) { - proc.on('close', process.exit.bind(process)) + proc.on('close', process.exit.bind(process)); proc.on('error', () => { - process.exit(1) - }) + process.exit(1); + }); } -const subCmd = program.args[0] +const subCmd = program.args[0]; if (!subCmd || subCmd !== 'run') { - program.help() + program.help(); } diff --git a/antd-tools/cli/run.js b/antd-tools/cli/run.js index 9842290fe..14e27131f 100644 --- a/antd-tools/cli/run.js +++ b/antd-tools/cli/run.js @@ -1,26 +1,26 @@ #!/usr/bin/env node -'use strict' +'use strict'; -require('colorful').colorful() -const gulp = require('gulp') -const program = require('commander') +require('colorful').colorful(); +const gulp = require('gulp'); +const program = require('commander'); program.on('--help', () => { - console.log(' Usage:'.to.bold.blue.color) - console.log() -}) + console.log(' Usage:'.to.bold.blue.color); + console.log(); +}); -program.parse(process.argv) +program.parse(process.argv); -const task = program.args[0] +const task = program.args[0]; if (!task) { - program.help() + program.help(); } else { - console.log('antd-tools run', task) + console.log('antd-tools run', task); - require('../gulpfile') + require('../gulpfile'); - gulp.start(task) + gulp.start(task); } diff --git a/antd-tools/getBabelCommonConfig.js b/antd-tools/getBabelCommonConfig.js index e840044ec..1b8c6e8fd 100644 --- a/antd-tools/getBabelCommonConfig.js +++ b/antd-tools/getBabelCommonConfig.js @@ -1,6 +1,6 @@ -'use strict' +'use strict'; -module.exports = function (modules) { +module.exports = function(modules) { const plugins = [ require.resolve('babel-plugin-transform-vue-jsx'), require.resolve('babel-plugin-transform-es3-member-expression-literals'), @@ -8,25 +8,31 @@ module.exports = function (modules) { require.resolve('babel-plugin-transform-object-assign'), require.resolve('babel-plugin-transform-object-rest-spread'), require.resolve('babel-plugin-transform-class-properties'), - ] - plugins.push([require.resolve('babel-plugin-transform-runtime'), { - polyfill: false, - }]) + ]; + plugins.push([ + require.resolve('babel-plugin-transform-runtime'), + { + polyfill: false, + }, + ]); return { presets: [ - [require.resolve('babel-preset-env'), { - modules, - targets: { - browsers: [ - 'last 2 versions', - 'Firefox ESR', - '> 1%', - 'ie >= 9', - 'iOS >= 8', - 'Android >= 4', - ], + [ + require.resolve('babel-preset-env'), + { + modules, + targets: { + browsers: [ + 'last 2 versions', + 'Firefox ESR', + '> 1%', + 'ie >= 9', + 'iOS >= 8', + 'Android >= 4', + ], + }, }, - }], + ], ], plugins, env: { @@ -34,5 +40,5 @@ module.exports = function (modules) { plugins: [require.resolve('babel-plugin-istanbul')], }, }, - } -} + }; +}; diff --git a/antd-tools/getWebpackConfig.js b/antd-tools/getWebpackConfig.js index 1c10d1e19..e8bb243b1 100644 --- a/antd-tools/getWebpackConfig.js +++ b/antd-tools/getWebpackConfig.js @@ -1,14 +1,14 @@ -const path = require('path') -const webpack = require('webpack') -const ExtractTextPlugin = require('extract-text-webpack-plugin') -const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin') -const deepAssign = require('deep-assign') -const chalk = require('chalk') -const postcssConfig = require('./postcssConfig') -const distFileBaseName = 'antd' -module.exports = function (modules) { - const pkg = require(path.join(process.cwd(), 'package.json')) - const babelConfig = require('./getBabelCommonConfig')(modules || false) +const path = require('path'); +const webpack = require('webpack'); +const ExtractTextPlugin = require('extract-text-webpack-plugin'); +const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); +const deepAssign = require('deep-assign'); +const chalk = require('chalk'); +const postcssConfig = require('./postcssConfig'); +const distFileBaseName = 'antd'; +module.exports = function(modules) { + const pkg = require(path.join(process.cwd(), 'package.json')); + const babelConfig = require('./getBabelCommonConfig')(modules || false); const pluginImportOptions = [ { @@ -16,17 +16,12 @@ module.exports = function (modules) { libraryName: 'antd', libraryDirectory: 'components', }, - ] + ]; // if (distFileBaseName !== 'antd') { pluginImportOptions.push({ style: // 'css', libraryDirectory: 'components', libraryName: 'antd', }) } - babelConfig - .plugins - .push([ - require.resolve('babel-plugin-import'), - pluginImportOptions, - ]) + babelConfig.plugins.push([require.resolve('babel-plugin-import'), pluginImportOptions]); const config = { devtool: 'source-map', @@ -37,14 +32,10 @@ module.exports = function (modules) { }, resolve: { - modules: [ - 'node_modules', path.join(__dirname, '../node_modules'), - ], - extensions: [ - '.js', '.jsx', '.vue', '.md', '.json', - ], + modules: ['node_modules', path.join(__dirname, '../node_modules')], + extensions: ['.js', '.jsx', '.vue', '.md', '.json'], alias: { - 'vue$': 'vue/dist/vue.esm.js', + vue$: 'vue/dist/vue.esm.js', '@': process.cwd(), }, }, @@ -86,12 +77,14 @@ module.exports = function (modules) { }, }, ], - }, { + }, + { test: /\.(js|jsx)$/, loader: 'babel-loader', exclude: /node_modules/, options: babelConfig, - }, { + }, + { test: /\.css$/, use: ExtractTextPlugin.extract({ use: [ @@ -100,13 +93,15 @@ module.exports = function (modules) { options: { sourceMap: true, }, - }, { + }, + { loader: 'postcss-loader', options: Object.assign({}, postcssConfig, { sourceMap: true }), }, ], }), - }, { + }, + { test: /\.less$/, use: ExtractTextPlugin.extract({ use: [ @@ -115,10 +110,12 @@ module.exports = function (modules) { options: { sourceMap: true, }, - }, { + }, + { loader: 'postcss-loader', options: Object.assign({}, postcssConfig, { sourceMap: true }), - }, { + }, + { loader: 'less-loader', options: { sourceMap: true, @@ -140,23 +137,23 @@ Copyright 2017-present, ant-design-vue. All rights reserved. `), new webpack.ProgressPlugin((percentage, msg, addInfo) => { - const stream = process.stderr + const stream = process.stderr; if (stream.isTTY && percentage < 0.71) { - stream.cursorTo(0) - stream.write(`📦 ${chalk.magenta(msg)} (${chalk.magenta(addInfo)})`) - stream.clearLine(1) + stream.cursorTo(0); + stream.write(`📦 ${chalk.magenta(msg)} (${chalk.magenta(addInfo)})`); + stream.clearLine(1); } else if (percentage === 1) { - console.log(chalk.green('\nwebpack: bundle build is now finished.')) + console.log(chalk.green('\nwebpack: bundle build is now finished.')); } }), ], - } + }; if (process.env.RUN_ENV === 'PRODUCTION') { - const entry = ['./index'] + const entry = ['./index']; config.entry = { [`${distFileBaseName}.min`]: entry, - } + }; config.externals = { vue: { root: 'Vue', @@ -164,47 +161,41 @@ All rights reserved. commonjs: 'vue', amd: 'vue', }, - } - config.output.library = distFileBaseName - config.output.libraryTarget = 'umd' + }; + config.output.library = distFileBaseName; + config.output.libraryTarget = 'umd'; - const uncompressedConfig = deepAssign({}, config) + const uncompressedConfig = deepAssign({}, config); - config.plugins = config - .plugins - .concat([ - new webpack - .optimize - .UglifyJsPlugin({ - sourceMap: true, - output: { - ascii_only: true, - }, - compress: { - warnings: false, - }, - }), - new webpack - .optimize - .ModuleConcatenationPlugin(), - new webpack.LoaderOptionsPlugin({ minimize: true }), - new webpack.DefinePlugin({ - 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'), - }), - ]) + config.plugins = config.plugins.concat([ + new webpack.optimize.UglifyJsPlugin({ + sourceMap: true, + output: { + ascii_only: true, + }, + compress: { + warnings: false, + }, + }), + new webpack.optimize.ModuleConcatenationPlugin(), + new webpack.LoaderOptionsPlugin({ minimize: true }), + new webpack.DefinePlugin({ + 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'), + }), + ]); uncompressedConfig.entry = { [distFileBaseName]: entry, - } + }; - uncompressedConfig - .plugins - .push(new webpack.DefinePlugin({ + uncompressedConfig.plugins.push( + new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development'), - })) + }), + ); - return [config, uncompressedConfig] + return [config, uncompressedConfig]; } - return config -} + return config; +}; diff --git a/antd-tools/gulpfile.js b/antd-tools/gulpfile.js index d5ad3d4e5..320f98321 100644 --- a/antd-tools/gulpfile.js +++ b/antd-tools/gulpfile.js @@ -1,57 +1,57 @@ -'use strict' +'use strict'; // const install = require('./install') -const runCmd = require('./runCmd') -const getBabelCommonConfig = require('./getBabelCommonConfig') -const merge2 = require('merge2') -const { execSync } = require('child_process') -const through2 = require('through2') -const transformLess = require('./transformLess') -const webpack = require('webpack') -const babel = require('gulp-babel') -const argv = require('minimist')(process.argv.slice(2)) -const GitHub = require('@octokit/rest') +const runCmd = require('./runCmd'); +const getBabelCommonConfig = require('./getBabelCommonConfig'); +const merge2 = require('merge2'); +const { execSync } = require('child_process'); +const through2 = require('through2'); +const transformLess = require('./transformLess'); +const webpack = require('webpack'); +const babel = require('gulp-babel'); +const argv = require('minimist')(process.argv.slice(2)); +const GitHub = require('@octokit/rest'); -const packageJson = require(`${process.cwd()}/package.json`) +const packageJson = require(`${process.cwd()}/package.json`); // const getNpm = require('./getNpm') // const selfPackage = require('../package.json') -const chalk = require('chalk') -const getNpmArgs = require('./utils/get-npm-args') -const getChangelog = require('./utils/getChangelog') -const path = require('path') +const chalk = require('chalk'); +const getNpmArgs = require('./utils/get-npm-args'); +const getChangelog = require('./utils/getChangelog'); +const path = require('path'); // const watch = require('gulp-watch') -const gulp = require('gulp') -const fs = require('fs') -const rimraf = require('rimraf') -const replaceLib = require('./replaceLib') -const stripCode = require('gulp-strip-code') -const compareVersions = require('compare-versions') +const gulp = require('gulp'); +const fs = require('fs'); +const rimraf = require('rimraf'); +const replaceLib = require('./replaceLib'); +const stripCode = require('gulp-strip-code'); +const compareVersions = require('compare-versions'); -const cwd = process.cwd() -const libDir = path.join(cwd, 'lib') -const esDir = path.join(cwd, 'es') +const cwd = process.cwd(); +const libDir = path.join(cwd, 'lib'); +const esDir = path.join(cwd, 'es'); -function dist (done) { - rimraf.sync(path.join(cwd, 'dist')) - process.env.RUN_ENV = 'PRODUCTION' - const webpackConfig = require(path.join(cwd, 'webpack.build.config.js')) +function dist(done) { + rimraf.sync(path.join(cwd, 'dist')); + process.env.RUN_ENV = 'PRODUCTION'; + const webpackConfig = require(path.join(cwd, 'webpack.build.config.js')); webpack(webpackConfig, (err, stats) => { if (err) { - console.error(err.stack || err) + console.error(err.stack || err); if (err.details) { - console.error(err.details) + console.error(err.details); } - return + return; } - const info = stats.toJson() + const info = stats.toJson(); if (stats.hasErrors()) { - console.error(info.errors) + console.error(info.errors); } if (stats.hasWarnings()) { - console.warn(info.warnings) + console.warn(info.warnings); } const buildInfo = stats.toString({ @@ -62,109 +62,126 @@ function dist (done) { chunkModules: false, hash: false, version: false, - }) - console.log(buildInfo) - done(0) - }) + }); + console.log(buildInfo); + done(0); + }); } -function babelify (js, modules) { - const babelConfig = getBabelCommonConfig(modules) - babelConfig.babelrc = false - delete babelConfig.cacheDirectory +function babelify(js, modules) { + const babelConfig = getBabelCommonConfig(modules); + babelConfig.babelrc = false; + delete babelConfig.cacheDirectory; if (modules === false) { - babelConfig.plugins.push(replaceLib) + babelConfig.plugins.push(replaceLib); } else { - babelConfig.plugins.push(require.resolve('babel-plugin-add-module-exports')) + babelConfig.plugins.push(require.resolve('babel-plugin-add-module-exports')); } - let stream = js.pipe(babel(babelConfig)) - .pipe(through2.obj(function z (file, encoding, next) { - this.push(file.clone()) + let stream = js.pipe(babel(babelConfig)).pipe( + through2.obj(function z(file, encoding, next) { + this.push(file.clone()); if (file.path.match(/\/style\/index\.(js|jsx)$/)) { - const content = file.contents.toString(encoding) - file.contents = Buffer.from(content - .replace(/\/style\/?'/g, '/style/css\'') - .replace(/\.less/g, '.css')) - file.path = file.path.replace(/index\.(js|jsx)$/, 'css.js') - this.push(file) - next() + const content = file.contents.toString(encoding); + file.contents = Buffer.from( + content.replace(/\/style\/?'/g, "/style/css'").replace(/\.less/g, '.css'), + ); + file.path = file.path.replace(/index\.(js|jsx)$/, 'css.js'); + this.push(file); + next(); } else { - next() + next(); } - })) + }), + ); if (modules === false) { - stream = stream.pipe(stripCode({ - start_comment: '@remove-on-es-build-begin', - end_comment: '@remove-on-es-build-end', - })) + stream = stream.pipe( + stripCode({ + start_comment: '@remove-on-es-build-begin', + end_comment: '@remove-on-es-build-end', + }), + ); } - return stream.pipe(gulp.dest(modules === false ? esDir : libDir)) + return stream.pipe(gulp.dest(modules === false ? esDir : libDir)); } -function compile (modules) { - rimraf.sync(modules !== false ? libDir : esDir) - const less = gulp.src(['components/**/*.less']) - .pipe(through2.obj(function (file, encoding, next) { - this.push(file.clone()) - if (file.path.match(/\/style\/index\.less$/) || file.path.match(/\/style\/v2-compatible-reset\.less$/)) { - transformLess(file.path).then((css) => { - file.contents = Buffer.from(css) - file.path = file.path.replace(/\.less$/, '.css') - this.push(file) - next() - }).catch((e) => { - console.error(e) - }) - } else { - next() - } - })) - .pipe(gulp.dest(modules === false ? esDir : libDir)) - const assets = gulp.src(['components/**/*.@(png|svg)']).pipe(gulp.dest(modules === false ? esDir : libDir)) +function compile(modules) { + rimraf.sync(modules !== false ? libDir : esDir); + const less = gulp + .src(['components/**/*.less']) + .pipe( + through2.obj(function(file, encoding, next) { + this.push(file.clone()); + if ( + file.path.match(/\/style\/index\.less$/) || + file.path.match(/\/style\/v2-compatible-reset\.less$/) + ) { + transformLess(file.path) + .then(css => { + file.contents = Buffer.from(css); + file.path = file.path.replace(/\.less$/, '.css'); + this.push(file); + next(); + }) + .catch(e => { + console.error(e); + }); + } else { + next(); + } + }), + ) + .pipe(gulp.dest(modules === false ? esDir : libDir)); + const assets = gulp + .src(['components/**/*.@(png|svg)']) + .pipe(gulp.dest(modules === false ? esDir : libDir)); - const source = [ - 'components/**/*.js', - 'components/**/*.jsx', - '!components/*/__tests__/*', - ] - const jsFilesStream = babelify(gulp.src(source), modules) - return merge2([less, jsFilesStream, assets]) + const source = ['components/**/*.js', 'components/**/*.jsx', '!components/*/__tests__/*']; + const jsFilesStream = babelify(gulp.src(source), modules); + return merge2([less, jsFilesStream, assets]); } -function tag () { - console.log('tagging') - const { version } = packageJson - execSync(`git config --global user.email ${process.env.GITHUB_USER_EMAIL}`) - execSync(`git config --global user.name ${process.env.GITHUB_USER_NAME}`) - execSync(`git tag ${version}`) - execSync(`git push https://${process.env.GITHUB_TOKEN}@github.com/vueComponent/ant-design-vue.git ${version}:${version}`) - execSync(`git push https://${process.env.GITHUB_TOKEN}@github.com/vueComponent/ant-design-vue.git master:master`) - console.log('tagged') +function tag() { + console.log('tagging'); + const { version } = packageJson; + execSync(`git config --global user.email ${process.env.GITHUB_USER_EMAIL}`); + execSync(`git config --global user.name ${process.env.GITHUB_USER_NAME}`); + execSync(`git tag ${version}`); + execSync( + `git push https://${ + process.env.GITHUB_TOKEN + }@github.com/vueComponent/ant-design-vue.git ${version}:${version}`, + ); + execSync( + `git push https://${ + process.env.GITHUB_TOKEN + }@github.com/vueComponent/ant-design-vue.git master:master`, + ); + console.log('tagged'); } -function githubRelease (done) { +function githubRelease(done) { const changlogFiles = [ path.join(cwd, 'CHANGELOG.en-US.md'), path.join(cwd, 'CHANGELOG.zh-CN.md'), - ] - console.log('creating release on GitHub') + ]; + console.log('creating release on GitHub'); if (!process.env.GITHUB_TOKEN) { - console.log('no GitHub token found, skip') - return + console.log('no GitHub token found, skip'); + return; } if (!changlogFiles.every(file => fs.existsSync(file))) { - console.log('no changelog found, skip') - return + console.log('no changelog found, skip'); + return; } - const github = new GitHub() + const github = new GitHub(); github.authenticate({ type: 'oauth', token: process.env.GITHUB_TOKEN, - }) - const date = new Date() - const { version } = packageJson - const enChangelog = getChangelog(changlogFiles[0], version) - const cnChangelog = getChangelog(changlogFiles[1], version) + }); + const date = new Date(); + const { version } = packageJson; + const enChangelog = getChangelog(changlogFiles[0], version); + const cnChangelog = getChangelog(changlogFiles[1], version); const changelog = [ `\`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}\``, enChangelog, @@ -172,161 +189,164 @@ function githubRelease (done) { '---', '\n', cnChangelog, - ].join('\n') + ].join('\n'); const [_, owner, repo] = execSync('git remote get-url origin') // eslint-disable-line .toString() - .match(/github.com[:/](.+)\/(.+)\.git/) - github.repos.createRelease({ - owner, - repo, - tag_name: version, - name: version, - body: changelog, - }).then(() => { - done() - }) + .match(/github.com[:/](.+)\/(.+)\.git/); + github.repos + .createRelease({ + owner, + repo, + tag_name: version, + name: version, + body: changelog, + }) + .then(() => { + done(); + }); } -gulp.task('tag', (done) => { - tag() - githubRelease(done) -}) +gulp.task('tag', done => { + tag(); + githubRelease(done); +}); -gulp.task('check-git', (done) => { +gulp.task('check-git', done => { runCmd('git', ['status', '--porcelain'], (code, result) => { if (/^\?\?/m.test(result)) { return done(`There are untracked files in the working tree.\n${result} - `) + `); } if (/^([ADRM]| [ADRM])/m.test(result)) { return done(`There are uncommitted changes in the working tree.\n${result} - `) + `); } - return done() - }) -}) + return done(); + }); +}); -function publish (tagString, done) { - let args = ['publish', '--with-antd-tools'] +function publish(tagString, done) { + let args = ['publish', '--with-antd-tools']; if (tagString) { - args = args.concat(['--tag', tagString]) + args = args.concat(['--tag', tagString]); } - const publishNpm = process.env.PUBLISH_NPM_CLI || 'npm' - runCmd(publishNpm, args, (code) => { - tag() + const publishNpm = process.env.PUBLISH_NPM_CLI || 'npm'; + runCmd(publishNpm, args, code => { + tag(); githubRelease(() => { - done(code) - }) - }) + done(code); + }); + }); } -function pub (done) { - dist((code) => { +function pub(done) { + dist(code => { if (code) { - done(code) - return + done(code); + return; } - const notOk = !packageJson.version.match(/^\d+\.\d+\.\d+$/) - let tagString + const notOk = !packageJson.version.match(/^\d+\.\d+\.\d+$/); + let tagString; if (argv['npm-tag']) { - tagString = argv['npm-tag'] + tagString = argv['npm-tag']; } if (!tagString && notOk) { - tagString = 'next' + tagString = 'next'; } if (packageJson.scripts['pre-publish']) { - runCmd('npm', ['run', 'pre-publish'], (code2) => { + runCmd('npm', ['run', 'pre-publish'], code2 => { if (code2) { - done(code2) - return + done(code2); + return; } - publish(tagString, done) - }) + publish(tagString, done); + }); } else { - publish(tagString, done) + publish(tagString, done); } - }) + }); } -gulp.task('dist', ['compile'], (done) => { - dist(done) -}) -gulp.task('compile', ['compile-with-es'], (done) => { - compile() - .on('finish', function () { - done() - }) -}) -gulp.task('compile-with-es', (done) => { - compile(false) - .on('finish', function () { - done() - }) -}) +gulp.task('dist', ['compile'], done => { + dist(done); +}); +gulp.task('compile', ['compile-with-es'], done => { + compile().on('finish', function() { + done(); + }); +}); +gulp.task('compile-with-es', done => { + compile(false).on('finish', function() { + done(); + }); +}); -gulp.task('pub', ['check-git', 'compile'], (done) => { +gulp.task('pub', ['check-git', 'compile'], done => { if (!process.env.GITHUB_TOKEN) { - console.log('no GitHub token found, skip') + console.log('no GitHub token found, skip'); } else { - pub(done) + pub(done); } -}) +}); -gulp.task('pub-with-ci', (done) => { +gulp.task('pub-with-ci', done => { if (!process.env.NPM_TOKEN) { - console.log('no NPM token found, skip') + console.log('no NPM token found, skip'); } else { - const github = new GitHub() + const github = new GitHub(); github.authenticate({ type: 'oauth', token: process.env.GITHUB_TOKEN, - }) + }); const [_, owner, repo] = execSync('git remote get-url origin') // eslint-disable-line .toString() - .match(/github.com[:/](.+)\/(.+)\.git/) + .match(/github.com[:/](.+)\/(.+)\.git/); const getLatestRelease = github.repos.getLatestRelease({ owner, repo, - }) + }); const getCommits = github.repos.getCommits({ owner, repo, per_page: 1, - }) + }); Promise.all([getLatestRelease, getCommits]).then(([latestRelease, commits]) => { - const preVersion = latestRelease.data.tag_name - const { version } = packageJson - const [_, newVersion] = commits.data[0].commit.message.trim().match(/bump (.+)/) || [] - if (compareVersions(version, preVersion) === 1 && newVersion && newVersion.trim() === version) { - gulp.run('pub', (err) => { - err && console.log('err', err) - done() - }) + const preVersion = latestRelease.data.tag_name; + const { version } = packageJson; + const [_, newVersion] = commits.data[0].commit.message.trim().match(/bump (.+)/) || []; // eslint-disable-line + if ( + compareVersions(version, preVersion) === 1 && + newVersion && + newVersion.trim() === version + ) { + gulp.run('pub', err => { + err && console.log('err', err); + done(); + }); } else { - console.log('donot need publish' + version) + console.log('donot need publish' + version); } - }) + }); } -}) +}); -function reportError () { - console.log(chalk.bgRed('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')) - console.log(chalk.bgRed('!! `npm publish` is forbidden for this package. !!')) - console.log(chalk.bgRed('!! Use `npm run pub` instead. !!')) - console.log(chalk.bgRed('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')) +function reportError() { + console.log(chalk.bgRed('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')); + console.log(chalk.bgRed('!! `npm publish` is forbidden for this package. !!')); + console.log(chalk.bgRed('!! Use `npm run pub` instead. !!')); + console.log(chalk.bgRed('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')); } -gulp.task('guard', (done) => { - const npmArgs = getNpmArgs() +gulp.task('guard', done => { + const npmArgs = getNpmArgs(); if (npmArgs) { for (let arg = npmArgs.shift(); arg; arg = npmArgs.shift()) { if (/^pu(b(l(i(sh?)?)?)?)?$/.test(arg) && npmArgs.indexOf('--with-antd-tools') < 0) { - reportError() - done(1) - return + reportError(); + done(1); + return; } } } - done() -}) - + done(); +}); diff --git a/antd-tools/postcssConfig.js b/antd-tools/postcssConfig.js index 47ea4a3ba..cd384eb5d 100644 --- a/antd-tools/postcssConfig.js +++ b/antd-tools/postcssConfig.js @@ -1,18 +1,11 @@ -const rucksack = require('rucksack-css') -const autoprefixer = require('autoprefixer') +const rucksack = require('rucksack-css'); +const autoprefixer = require('autoprefixer'); module.exports = { plugins: [ rucksack(), autoprefixer({ - browsers: [ - 'last 2 versions', - 'Firefox ESR', - '> 1%', - 'ie >= 9', - 'iOS >= 8', - 'Android >= 4', - ], + browsers: ['last 2 versions', 'Firefox ESR', '> 1%', 'ie >= 9', 'iOS >= 8', 'Android >= 4'], }), ], -} +}; diff --git a/antd-tools/replaceLib.js b/antd-tools/replaceLib.js index cd92ebebb..e1eaeb065 100644 --- a/antd-tools/replaceLib.js +++ b/antd-tools/replaceLib.js @@ -1,27 +1,27 @@ -'use strict' +'use strict'; -const { join, dirname } = require('path') -const fs = require('fs') +const { join, dirname } = require('path'); +const fs = require('fs'); -const cwd = process.cwd() +const cwd = process.cwd(); -function replacePath (path) { +function replacePath(path) { if (path.node.source && /\/lib\//.test(path.node.source.value)) { - const esModule = path.node.source.value.replace('/lib/', '/es/') - const esPath = dirname(join(cwd, `node_modules/${esModule}`)) + const esModule = path.node.source.value.replace('/lib/', '/es/'); + const esPath = dirname(join(cwd, `node_modules/${esModule}`)); if (fs.existsSync(esPath)) { - path.node.source.value = esModule + path.node.source.value = esModule; } } } -function replaceLib () { +function replaceLib() { return { visitor: { ImportDeclaration: replacePath, ExportNamedDeclaration: replacePath, }, - } + }; } -module.exports = replaceLib +module.exports = replaceLib; diff --git a/antd-tools/runCmd.js b/antd-tools/runCmd.js index d3c0bd64f..f5a822a97 100644 --- a/antd-tools/runCmd.js +++ b/antd-tools/runCmd.js @@ -1,20 +1,20 @@ -'use strict' +'use strict'; -const getRunCmdEnv = require('./utils/getRunCmdEnv') +const getRunCmdEnv = require('./utils/getRunCmdEnv'); -function runCmd (cmd, _args, fn) { - const args = _args || [] +function runCmd(cmd, _args, fn) { + const args = _args || []; const runner = require('child_process').spawn(cmd, args, { // keep color stdio: 'inherit', env: getRunCmdEnv(), - }) + }); - runner.on('close', (code) => { + runner.on('close', code => { if (fn) { - fn(code) + fn(code); } - }) + }); } -module.exports = runCmd +module.exports = runCmd; diff --git a/antd-tools/transformLess.js b/antd-tools/transformLess.js index 2cbf8adeb..2a03eefe2 100644 --- a/antd-tools/transformLess.js +++ b/antd-tools/transformLess.js @@ -1,33 +1,32 @@ -const less = require('less') -const { readFileSync } = require('fs') -const path = require('path') -const postcss = require('postcss') -const NpmImportPlugin = require('less-plugin-npm-import') -const postcssConfig = require('./postcssConfig') +const less = require('less'); +const { readFileSync } = require('fs'); +const path = require('path'); +const postcss = require('postcss'); +const NpmImportPlugin = require('less-plugin-npm-import'); +const postcssConfig = require('./postcssConfig'); -function transformLess (lessFile, config = {}) { - const { cwd = process.cwd() } = config - const resolvedLessFile = path.resolve(cwd, lessFile) +function transformLess(lessFile, config = {}) { + const { cwd = process.cwd() } = config; + const resolvedLessFile = path.resolve(cwd, lessFile); - let data = readFileSync(resolvedLessFile, 'utf-8') - data = data.replace(/^\uFEFF/, '') + let data = readFileSync(resolvedLessFile, 'utf-8'); + data = data.replace(/^\uFEFF/, ''); // Do less compile const lessOpts = { paths: [path.dirname(resolvedLessFile)], filename: resolvedLessFile, - plugins: [ - new NpmImportPlugin({ prefix: '~' }), - ], - } - return less.render(data, lessOpts) - .then((result) => { - const source = result.css - return postcss(postcssConfig.plugins).process(source) - }) - .then((r) => { - return r.css + plugins: [new NpmImportPlugin({ prefix: '~' })], + }; + return less + .render(data, lessOpts) + .then(result => { + const source = result.css; + return postcss(postcssConfig.plugins).process(source); }) + .then(r => { + return r.css; + }); } -module.exports = transformLess +module.exports = transformLess; diff --git a/antd-tools/utils/get-npm-args.js b/antd-tools/utils/get-npm-args.js index 3006156ee..9de9013c1 100644 --- a/antd-tools/utils/get-npm-args.js +++ b/antd-tools/utils/get-npm-args.js @@ -1,18 +1,18 @@ -'use strict' +'use strict'; // NOTE: the following code was partially adopted from https://github.com/iarna/in-publish -module.exports = function getNpmArgs () { - let npmArgv = null +module.exports = function getNpmArgs() { + let npmArgv = null; try { - npmArgv = JSON.parse(process.env.npm_config_argv) + npmArgv = JSON.parse(process.env.npm_config_argv); } catch (err) { - return null + return null; } if (typeof npmArgv !== 'object' || !npmArgv.cooked || !Array.isArray(npmArgv.cooked)) { - return null + return null; } - return npmArgv.cooked -} + return npmArgv.cooked; +}; diff --git a/antd-tools/utils/getChangelog.js b/antd-tools/utils/getChangelog.js index d05718fd8..381183e94 100644 --- a/antd-tools/utils/getChangelog.js +++ b/antd-tools/utils/getChangelog.js @@ -1,23 +1,26 @@ -const fs = require('fs') +const fs = require('fs'); -module.exports = function getChangelog (file, version) { - const lines = fs.readFileSync(file).toString().split('\n') - const changeLog = [] - const startPattern = new RegExp(`^## ${version}`) - const stopPattern = /^## / // 前一个版本 - const skipPattern = /^`/ // 日期 - let begin = false +module.exports = function getChangelog(file, version) { + const lines = fs + .readFileSync(file) + .toString() + .split('\n'); + const changeLog = []; + const startPattern = new RegExp(`^## ${version}`); + const stopPattern = /^## /; // 前一个版本 + const skipPattern = /^`/; // 日期 + let begin = false; for (let i = 0; i < lines.length; i += 1) { - const line = lines[i] + const line = lines[i]; if (begin && stopPattern.test(line)) { - break + break; } if (begin && line && !skipPattern.test(line)) { - changeLog.push(line) + changeLog.push(line); } if (!begin) { - begin = startPattern.test(line) + begin = startPattern.test(line); } } - return changeLog.join('\n') -} + return changeLog.join('\n'); +}; diff --git a/antd-tools/utils/getRunCmdEnv.js b/antd-tools/utils/getRunCmdEnv.js index 48033b93c..d4cb7cc97 100644 --- a/antd-tools/utils/getRunCmdEnv.js +++ b/antd-tools/utils/getRunCmdEnv.js @@ -1,14 +1,14 @@ -'use strict' +'use strict'; -const path = require('path') +const path = require('path'); -module.exports = function getRunCmdEnv () { - const env = {} - Object.keys(process.env).forEach((key) => { - env[key] = process.env[key] - }) +module.exports = function getRunCmdEnv() { + const env = {}; + Object.keys(process.env).forEach(key => { + env[key] = process.env[key]; + }); // make sure `antd-tools/node_modules/.bin` in the PATH env - const nodeModulesBinDir = path.join(__dirname, '../../node_modules/.bin') - env.PATH = env.PATH ? `${nodeModulesBinDir}:${env.PATH}` : nodeModulesBinDir - return env -} + const nodeModulesBinDir = path.join(__dirname, '../../node_modules/.bin'); + env.PATH = env.PATH ? `${nodeModulesBinDir}:${env.PATH}` : nodeModulesBinDir; + return env; +}; diff --git a/components/_util/BaseMixin.js b/components/_util/BaseMixin.js index f01a6b5e3..fefcf18df 100644 --- a/components/_util/BaseMixin.js +++ b/components/_util/BaseMixin.js @@ -1,4 +1,3 @@ - export default { // directives: { // ref: { @@ -14,27 +13,28 @@ export default { // }, // }, methods: { - setState (state, callback) { - const newState = typeof state === 'function' ? state(this.$data, this.$props) : state + setState(state, callback) { + const newState = typeof state === 'function' ? state(this.$data, this.$props) : state; // if (this.getDerivedStateFromProps) { // Object.assign(newState, this.getDerivedStateFromProps(getOptionProps(this), { ...this.$data, ...newState }, true) || {}) // } - Object.assign(this.$data, newState) + Object.assign(this.$data, newState); this.$nextTick(() => { - callback && callback() - }) + callback && callback(); + }); }, - __emit () { // 直接调用listeners,底层组件不需要vueTool记录events - const args = [].slice.call(arguments, 0) - const filterEvent = [] - const eventName = args[0] + __emit() { + // 直接调用listeners,底层组件不需要vueTool记录events + const args = [].slice.call(arguments, 0); + const filterEvent = []; + const eventName = args[0]; if (args.length && this.$listeners[eventName]) { if (filterEvent.includes(eventName)) { - this.$emit(eventName, ...args.slice(1)) + this.$emit(eventName, ...args.slice(1)); } else { - this.$listeners[eventName](...args.slice(1)) + this.$listeners[eventName](...args.slice(1)); } } }, }, -} +}; diff --git a/components/_util/ContainerRender.jsx b/components/_util/ContainerRender.jsx index 66ffe52f2..958c58a5a 100644 --- a/components/_util/ContainerRender.jsx +++ b/components/_util/ContainerRender.jsx @@ -1,6 +1,5 @@ - -import Vue from 'vue' -import PropTypes from './vue-types' +import Vue from 'vue'; +import PropTypes from './vue-types'; export default { props: { @@ -14,42 +13,42 @@ export default { children: PropTypes.func.isRequired, }, - mounted () { + mounted() { if (this.autoMount) { - this.renderComponent() + this.renderComponent(); } }, - updated () { + updated() { if (this.autoMount) { - this.renderComponent() + this.renderComponent(); } }, - beforeDestroy () { + beforeDestroy() { if (this.autoDestroy) { - this.removeContainer() + this.removeContainer(); } }, methods: { - removeContainer () { + removeContainer() { if (this.container) { - this._component && this._component.$destroy() - this.container.parentNode.removeChild(this.container) - this.container = null + this._component && this._component.$destroy(); + this.container.parentNode.removeChild(this.container); + this.container = null; } }, - renderComponent (props = {}, ready) { - const { visible, forceRender, getContainer, parent } = this - const self = this + renderComponent(props = {}, ready) { + const { visible, forceRender, getContainer, parent } = this; + const self = this; if (visible || parent.$refs._component || forceRender) { - let el = this.componentEl + let el = this.componentEl; if (!this.container) { - this.container = getContainer() - el = document.createElement('div') - this.componentEl = el - this.container.appendChild(el) + this.container = getContainer(); + el = document.createElement('div'); + this.componentEl = el; + this.container.appendChild(el); } if (!this._component) { @@ -59,36 +58,35 @@ export default { }, parent: self.parent, el: el, - mounted () { + mounted() { this.$nextTick(() => { if (ready) { - ready.call(self) + ready.call(self); } - }) + }); }, - updated () { + updated() { this.$nextTick(() => { if (ready) { - ready.call(self) + ready.call(self); } - }) + }); }, - render () { - return self.getComponent(this.comProps) + render() { + return self.getComponent(this.comProps); }, - }) + }); } else { - this._component.comProps = props + this._component.comProps = props; } } }, }, - render () { + render() { return this.children({ renderComponent: this.renderComponent, removeContainer: this.removeContainer, - }) + }); }, -} - +}; diff --git a/components/_util/Dom/addEventListener.js b/components/_util/Dom/addEventListener.js index 4ea8998c8..4f93f9d79 100644 --- a/components/_util/Dom/addEventListener.js +++ b/components/_util/Dom/addEventListener.js @@ -1,5 +1,5 @@ -import addDOMEventListener from 'add-dom-event-listener' +import addDOMEventListener from 'add-dom-event-listener'; -export default function addEventListenerWrap (target, eventType, cb, option) { - return addDOMEventListener(target, eventType, cb, option) +export default function addEventListenerWrap(target, eventType, cb, option) { + return addDOMEventListener(target, eventType, cb, option); } diff --git a/components/_util/Dom/class-util.js b/components/_util/Dom/class-util.js index 2fbed21d9..5012f5722 100644 --- a/components/_util/Dom/class-util.js +++ b/components/_util/Dom/class-util.js @@ -4,23 +4,23 @@ * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ -export function addClass (el, cls) { +export function addClass(el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { - return + return; } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { - cls.split(/\s+/).forEach(c => el.classList.add(c)) + cls.split(/\s+/).forEach(c => el.classList.add(c)); } else { - el.classList.add(cls) + el.classList.add(cls); } } else { - const cur = ` ${el.getAttribute('class') || ''} ` + const cur = ` ${el.getAttribute('class') || ''} `; if (cur.indexOf(' ' + cls + ' ') < 0) { - el.setAttribute('class', (cur + cls).trim()) + el.setAttribute('class', (cur + cls).trim()); } } } @@ -29,33 +29,33 @@ export function addClass (el, cls) { * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ -export function removeClass (el, cls) { +export function removeClass(el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { - return + return; } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { - cls.split(/\s+/).forEach(c => el.classList.remove(c)) + cls.split(/\s+/).forEach(c => el.classList.remove(c)); } else { - el.classList.remove(cls) + el.classList.remove(cls); } if (!el.classList.length) { - el.removeAttribute('class') + el.removeAttribute('class'); } } else { - let cur = ` ${el.getAttribute('class') || ''} ` - const tar = ' ' + cls + ' ' + let cur = ` ${el.getAttribute('class') || ''} `; + const tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { - cur = cur.replace(tar, ' ') + cur = cur.replace(tar, ' '); } - cur = cur.trim() + cur = cur.trim(); if (cur) { - el.setAttribute('class', cur) + el.setAttribute('class', cur); } else { - el.removeAttribute('class') + el.removeAttribute('class'); } } } diff --git a/components/_util/Dom/contains.js b/components/_util/Dom/contains.js index f034a2d2e..0c4c465eb 100644 --- a/components/_util/Dom/contains.js +++ b/components/_util/Dom/contains.js @@ -1,11 +1,11 @@ -export default function contains (root, n) { - let node = n +export default function contains(root, n) { + let node = n; while (node) { if (node === root) { - return true + return true; } - node = node.parentNode + node = node.parentNode; } - return false + return false; } diff --git a/components/_util/FormDecoratorDirective.js b/components/_util/FormDecoratorDirective.js index 746f9dc4c..bfe9aa857 100644 --- a/components/_util/FormDecoratorDirective.js +++ b/components/_util/FormDecoratorDirective.js @@ -1,11 +1,10 @@ -export function antDecorator (Vue) { - return Vue.directive('decorator', { - }) +export function antDecorator(Vue) { + return Vue.directive('decorator', {}); } export default { // just for tag install: (Vue, options) => { - antDecorator(Vue) + antDecorator(Vue); }, -} +}; diff --git a/components/_util/KeyCode.js b/components/_util/KeyCode.js index 80bf34c0b..547263b9d 100644 --- a/components/_util/KeyCode.js +++ b/components/_util/KeyCode.js @@ -425,17 +425,20 @@ const KeyCode = { * WIN_IME */ WIN_IME: 229, -} +}; /* whether text and modified key is entered at the same time. */ -KeyCode.isTextModifyingKeyEvent = function isTextModifyingKeyEvent (e) { - const keyCode = e.keyCode - if (e.altKey && !e.ctrlKey || e.metaKey || - // Function keys don't generate text - keyCode >= KeyCode.F1 && keyCode <= KeyCode.F12) { - return false +KeyCode.isTextModifyingKeyEvent = function isTextModifyingKeyEvent(e) { + const keyCode = e.keyCode; + if ( + (e.altKey && !e.ctrlKey) || + e.metaKey || + // Function keys don't generate text + (keyCode >= KeyCode.F1 && keyCode <= KeyCode.F12) + ) { + return false; } // The following keys are quite harmless, even in combination with @@ -464,34 +467,31 @@ KeyCode.isTextModifyingKeyEvent = function isTextModifyingKeyEvent (e) { case KeyCode.UP: case KeyCode.WIN_KEY: case KeyCode.WIN_KEY_RIGHT: - return false + return false; default: - return true + return true; } -} +}; /* whether character is entered. */ -KeyCode.isCharacterKey = function isCharacterKey (keyCode) { - if (keyCode >= KeyCode.ZERO && - keyCode <= KeyCode.NINE) { - return true +KeyCode.isCharacterKey = function isCharacterKey(keyCode) { + if (keyCode >= KeyCode.ZERO && keyCode <= KeyCode.NINE) { + return true; } - if (keyCode >= KeyCode.NUM_ZERO && - keyCode <= KeyCode.NUM_MULTIPLY) { - return true + if (keyCode >= KeyCode.NUM_ZERO && keyCode <= KeyCode.NUM_MULTIPLY) { + return true; } - if (keyCode >= KeyCode.A && - keyCode <= KeyCode.Z) { - return true + if (keyCode >= KeyCode.A && keyCode <= KeyCode.Z) { + return true; } // Safari sends zero key code for non-latin characters. if (window.navigation.userAgent.indexOf('WebKit') !== -1 && keyCode === 0) { - return true + return true; } switch (keyCode) { @@ -512,10 +512,10 @@ KeyCode.isCharacterKey = function isCharacterKey (keyCode) { case KeyCode.OPEN_SQUARE_BRACKET: case KeyCode.BACKSLASH: case KeyCode.CLOSE_SQUARE_BRACKET: - return true + return true; default: - return false + return false; } -} +}; -export default KeyCode +export default KeyCode; diff --git a/components/_util/StateMixin.js b/components/_util/StateMixin.js index 7d491a886..d2ba6f938 100644 --- a/components/_util/StateMixin.js +++ b/components/_util/StateMixin.js @@ -1,10 +1,10 @@ export default { methods: { - setState (state, callback) { - Object.assign(this.$data, state) + setState(state, callback) { + Object.assign(this.$data, state); this.$nextTick(() => { - callback && callback() - }) + callback && callback(); + }); }, }, -} +}; diff --git a/components/_util/antDirective.js b/components/_util/antDirective.js index fb89c3135..08c416a14 100644 --- a/components/_util/antDirective.js +++ b/components/_util/antDirective.js @@ -1,9 +1,9 @@ -import { antInput } from './antInputDirective' -import { antDecorator } from './FormDecoratorDirective' +import { antInput } from './antInputDirective'; +import { antDecorator } from './FormDecoratorDirective'; export default { install: (Vue, options) => { - antInput(Vue) - antDecorator(Vue) + antInput(Vue); + antDecorator(Vue); }, -} +}; diff --git a/components/_util/antInputDirective.js b/components/_util/antInputDirective.js index aeba9f943..d4695057a 100644 --- a/components/_util/antInputDirective.js +++ b/components/_util/antInputDirective.js @@ -3,76 +3,71 @@ * properties to Elements. */ -export const inBrowser = typeof window !== 'undefined' -export const UA = inBrowser && window.navigator.userAgent.toLowerCase() -export const isIE9 = UA && UA.indexOf('msie 9.0') > 0 -function makeMap ( - str, - expectsLowerCase -) { - const map = Object.create(null) - const list = str.split(',') +export const inBrowser = typeof window !== 'undefined'; +export const UA = inBrowser && window.navigator.userAgent.toLowerCase(); +export const isIE9 = UA && UA.indexOf('msie 9.0') > 0; +function makeMap(str, expectsLowerCase) { + const map = Object.create(null); + const list = str.split(','); for (let i = 0; i < list.length; i++) { - map[list[i]] = true + map[list[i]] = true; } - return expectsLowerCase - ? val => map[val.toLowerCase()] - : val => map[val] + return expectsLowerCase ? val => map[val.toLowerCase()] : val => map[val]; } -const isTextInputType = makeMap('text,number,password,search,email,tel,url') +const isTextInputType = makeMap('text,number,password,search,email,tel,url'); -function onCompositionStart (e) { - e.target.composing = true +function onCompositionStart(e) { + e.target.composing = true; } -function onCompositionEnd (e) { +function onCompositionEnd(e) { // prevent triggering an input event for no reason - if (!e.target.composing) return - e.target.composing = false - trigger(e.target, 'input') + if (!e.target.composing) return; + e.target.composing = false; + trigger(e.target, 'input'); } -function trigger (el, type) { - const e = document.createEvent('HTMLEvents') - e.initEvent(type, true, true) - el.dispatchEvent(e) +function trigger(el, type) { + const e = document.createEvent('HTMLEvents'); + e.initEvent(type, true, true); + el.dispatchEvent(e); } /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', () => { - const el = document.activeElement + const el = document.activeElement; if (el && el.vmodel) { - trigger(el, 'input') + trigger(el, 'input'); } - }) + }); } -export function antInput (Vue) { +export function antInput(Vue) { return Vue.directive('ant-input', { - inserted (el, binding, vnode, oldVnode) { + inserted(el, binding, vnode, oldVnode) { if (vnode.tag === 'textarea' || isTextInputType(el.type)) { if (!binding.modifiers || !binding.modifiers.lazy) { - el.addEventListener('compositionstart', onCompositionStart) - el.addEventListener('compositionend', onCompositionEnd) + el.addEventListener('compositionstart', onCompositionStart); + el.addEventListener('compositionend', onCompositionEnd); // Safari < 10.2 & UIWebView doesn't fire compositionend when // switching focus before confirming composition choice // this also fixes the issue where some browsers e.g. iOS Chrome // fires "change" instead of "input" on autocomplete. - el.addEventListener('change', onCompositionEnd) + el.addEventListener('change', onCompositionEnd); /* istanbul ignore if */ if (isIE9) { - el.vmodel = true + el.vmodel = true; } } } }, - }) + }); } export default { install: (Vue, options) => { - antInput(Vue) + antInput(Vue); }, -} +}; diff --git a/components/_util/callMoment.js b/components/_util/callMoment.js index 3a3dc0ab9..3bb9a981d 100644 --- a/components/_util/callMoment.js +++ b/components/_util/callMoment.js @@ -1,4 +1,4 @@ // https://github.com/moment/moment/issues/3650 -export default function callMoment (moment, ...args) { - return (moment.default || moment)(...args) +export default function callMoment(moment, ...args) { + return (moment.default || moment)(...args); } diff --git a/components/_util/createChainedFunction.js b/components/_util/createChainedFunction.js index f9334e32e..3d1fd45a3 100644 --- a/components/_util/createChainedFunction.js +++ b/components/_util/createChainedFunction.js @@ -6,17 +6,17 @@ * * @returns {function|null} */ -export default function createChainedFunction () { - const args = [].slice.call(arguments, 0) +export default function createChainedFunction() { + const args = [].slice.call(arguments, 0); if (args.length === 1) { - return args[0] + return args[0]; } - return function chainedFunction () { + return function chainedFunction() { for (let i = 0; i < args.length; i++) { if (args[i] && args[i].apply) { - args[i].apply(this, arguments) + args[i].apply(this, arguments); } } - } + }; } diff --git a/components/_util/css-animation/Event.js b/components/_util/css-animation/Event.js index d35c67345..f156171e1 100644 --- a/components/_util/css-animation/Event.js +++ b/components/_util/css-animation/Event.js @@ -14,7 +14,7 @@ const START_EVENT_NAME_MAP = { OAnimation: 'oAnimationStart', msAnimation: 'MSAnimationStart', }, -} +}; const END_EVENT_NAME_MAP = { transitionend: { @@ -32,99 +32,99 @@ const END_EVENT_NAME_MAP = { OAnimation: 'oAnimationEnd', msAnimation: 'MSAnimationEnd', }, -} +}; -const startEvents = [] -const endEvents = [] +const startEvents = []; +const endEvents = []; -function detectEvents () { - const testEl = document.createElement('div') - const style = testEl.style +function detectEvents() { + const testEl = document.createElement('div'); + const style = testEl.style; if (!('AnimationEvent' in window)) { - delete START_EVENT_NAME_MAP.animationstart.animation - delete END_EVENT_NAME_MAP.animationend.animation + delete START_EVENT_NAME_MAP.animationstart.animation; + delete END_EVENT_NAME_MAP.animationend.animation; } if (!('TransitionEvent' in window)) { - delete START_EVENT_NAME_MAP.transitionstart.transition - delete END_EVENT_NAME_MAP.transitionend.transition + delete START_EVENT_NAME_MAP.transitionstart.transition; + delete END_EVENT_NAME_MAP.transitionend.transition; } - function process (EVENT_NAME_MAP, events) { + function process(EVENT_NAME_MAP, events) { for (const baseEventName in EVENT_NAME_MAP) { if (EVENT_NAME_MAP.hasOwnProperty(baseEventName)) { - const baseEvents = EVENT_NAME_MAP[baseEventName] + const baseEvents = EVENT_NAME_MAP[baseEventName]; for (const styleName in baseEvents) { if (styleName in style) { - events.push(baseEvents[styleName]) - break + events.push(baseEvents[styleName]); + break; } } } } } - process(START_EVENT_NAME_MAP, startEvents) - process(END_EVENT_NAME_MAP, endEvents) + process(START_EVENT_NAME_MAP, startEvents); + process(END_EVENT_NAME_MAP, endEvents); } if (typeof window !== 'undefined' && typeof document !== 'undefined') { - detectEvents() + detectEvents(); } -function addEventListener (node, eventName, eventListener) { - node.addEventListener(eventName, eventListener, false) +function addEventListener(node, eventName, eventListener) { + node.addEventListener(eventName, eventListener, false); } -function removeEventListener (node, eventName, eventListener) { - node.removeEventListener(eventName, eventListener, false) +function removeEventListener(node, eventName, eventListener) { + node.removeEventListener(eventName, eventListener, false); } const TransitionEvents = { // Start events startEvents, - addStartEventListener (node, eventListener) { + addStartEventListener(node, eventListener) { if (startEvents.length === 0) { - window.setTimeout(eventListener, 0) - return + window.setTimeout(eventListener, 0); + return; } - startEvents.forEach((startEvent) => { - addEventListener(node, startEvent, eventListener) - }) + startEvents.forEach(startEvent => { + addEventListener(node, startEvent, eventListener); + }); }, - removeStartEventListener (node, eventListener) { + removeStartEventListener(node, eventListener) { if (startEvents.length === 0) { - return + return; } - startEvents.forEach((startEvent) => { - removeEventListener(node, startEvent, eventListener) - }) + startEvents.forEach(startEvent => { + removeEventListener(node, startEvent, eventListener); + }); }, // End events endEvents, - addEndEventListener (node, eventListener) { + addEndEventListener(node, eventListener) { if (endEvents.length === 0) { - window.setTimeout(eventListener, 0) - return + window.setTimeout(eventListener, 0); + return; } - endEvents.forEach((endEvent) => { - addEventListener(node, endEvent, eventListener) - }) + endEvents.forEach(endEvent => { + addEventListener(node, endEvent, eventListener); + }); }, - removeEndEventListener (node, eventListener) { + removeEndEventListener(node, eventListener) { if (endEvents.length === 0) { - return + return; } - endEvents.forEach((endEvent) => { - removeEventListener(node, endEvent, eventListener) - }) + endEvents.forEach(endEvent => { + removeEventListener(node, endEvent, eventListener); + }); }, -} +}; -export default TransitionEvents +export default TransitionEvents; diff --git a/components/_util/css-animation/index.js b/components/_util/css-animation/index.js index 0766ff613..5cc53fa07 100644 --- a/components/_util/css-animation/index.js +++ b/components/_util/css-animation/index.js @@ -1,181 +1,181 @@ // https://github.com/yiminghe/css-animation 1.5.0 -import Event from './Event' -import classes from 'component-classes' -import { requestAnimationTimeout, cancelAnimationTimeout } from '../requestAnimationTimeout' +import Event from './Event'; +import classes from 'component-classes'; +import { requestAnimationTimeout, cancelAnimationTimeout } from '../requestAnimationTimeout'; -const isCssAnimationSupported = Event.endEvents.length !== 0 -const capitalPrefixes = ['Webkit', +const isCssAnimationSupported = Event.endEvents.length !== 0; +const capitalPrefixes = [ + 'Webkit', 'Moz', 'O', // ms is special .... ! - 'ms'] -const prefixes = ['-webkit-', '-moz-', '-o-', 'ms-', ''] + 'ms', +]; +const prefixes = ['-webkit-', '-moz-', '-o-', 'ms-', '']; -function getStyleProperty (node, name) { +function getStyleProperty(node, name) { // old ff need null, https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle - const style = window.getComputedStyle(node, null) - let ret = '' + const style = window.getComputedStyle(node, null); + let ret = ''; for (let i = 0; i < prefixes.length; i++) { - ret = style.getPropertyValue(prefixes[i] + name) + ret = style.getPropertyValue(prefixes[i] + name); if (ret) { - break + break; } } - return (ret) + return ret; } -function fixBrowserByTimeout (node) { +function fixBrowserByTimeout(node) { if (isCssAnimationSupported) { - const transitionDelay = parseFloat(getStyleProperty(node, 'transition-delay')) || 0 - const transitionDuration = parseFloat(getStyleProperty(node, 'transition-duration')) || 0 - const animationDelay = parseFloat(getStyleProperty(node, 'animation-delay')) || 0 - const animationDuration = parseFloat(getStyleProperty(node, 'animation-duration')) || 0 - const time = Math.max(transitionDuration + transitionDelay, animationDuration + animationDelay) + const transitionDelay = parseFloat(getStyleProperty(node, 'transition-delay')) || 0; + const transitionDuration = parseFloat(getStyleProperty(node, 'transition-duration')) || 0; + const animationDelay = parseFloat(getStyleProperty(node, 'animation-delay')) || 0; + const animationDuration = parseFloat(getStyleProperty(node, 'animation-duration')) || 0; + const time = Math.max(transitionDuration + transitionDelay, animationDuration + animationDelay); // sometimes, browser bug node.rcEndAnimTimeout = setTimeout(() => { - node.rcEndAnimTimeout = null + node.rcEndAnimTimeout = null; if (node.rcEndListener) { - node.rcEndListener() + node.rcEndListener(); } - }, (time) * 1000 + 200) + }, time * 1000 + 200); } } -function clearBrowserBugTimeout (node) { +function clearBrowserBugTimeout(node) { if (node.rcEndAnimTimeout) { - clearTimeout(node.rcEndAnimTimeout) - node.rcEndAnimTimeout = null + clearTimeout(node.rcEndAnimTimeout); + node.rcEndAnimTimeout = null; } } const cssAnimation = (node, transitionName, endCallback) => { - const nameIsObj = typeof transitionName === 'object' - const className = nameIsObj ? transitionName.name : transitionName - const activeClassName = nameIsObj ? transitionName.active : `${transitionName}-active` - let end = endCallback - let start - let active - const nodeClasses = classes(node) + const nameIsObj = typeof transitionName === 'object'; + const className = nameIsObj ? transitionName.name : transitionName; + const activeClassName = nameIsObj ? transitionName.active : `${transitionName}-active`; + let end = endCallback; + let start; + let active; + const nodeClasses = classes(node); if (endCallback && Object.prototype.toString.call(endCallback) === '[object Object]') { - end = endCallback.end - start = endCallback.start - active = endCallback.active + end = endCallback.end; + start = endCallback.start; + active = endCallback.active; } if (node.rcEndListener) { - node.rcEndListener() + node.rcEndListener(); } - node.rcEndListener = (e) => { + node.rcEndListener = e => { if (e && e.target !== node) { - return + return; } if (node.rcAnimTimeout) { - cancelAnimationTimeout(node.rcAnimTimeout) - node.rcAnimTimeout = null + cancelAnimationTimeout(node.rcAnimTimeout); + node.rcAnimTimeout = null; } - clearBrowserBugTimeout(node) + clearBrowserBugTimeout(node); - nodeClasses.remove(className) - nodeClasses.remove(activeClassName) + nodeClasses.remove(className); + nodeClasses.remove(activeClassName); - Event.removeEndEventListener(node, node.rcEndListener) - node.rcEndListener = null + Event.removeEndEventListener(node, node.rcEndListener); + node.rcEndListener = null; // Usually this optional end is used for informing an owner of // a leave animation and telling it to remove the child. if (end) { - end() + end(); } - } + }; - Event.addEndEventListener(node, node.rcEndListener) + Event.addEndEventListener(node, node.rcEndListener); if (start) { - start() + start(); } - nodeClasses.add(className) + nodeClasses.add(className); node.rcAnimTimeout = requestAnimationTimeout(() => { - node.rcAnimTimeout = null - nodeClasses.add(activeClassName) + node.rcAnimTimeout = null; + nodeClasses.add(activeClassName); if (active) { - requestAnimationTimeout(active, 0) + requestAnimationTimeout(active, 0); } - fixBrowserByTimeout(node) + fixBrowserByTimeout(node); // 30ms for firefox - }, 30) + }, 30); return { - stop () { + stop() { if (node.rcEndListener) { - node.rcEndListener() + node.rcEndListener(); } }, - } -} + }; +}; cssAnimation.style = (node, style, callback) => { if (node.rcEndListener) { - node.rcEndListener() + node.rcEndListener(); } - node.rcEndListener = (e) => { + node.rcEndListener = e => { if (e && e.target !== node) { - return + return; } if (node.rcAnimTimeout) { - cancelAnimationTimeout(node.rcAnimTimeout) - node.rcAnimTimeout = null + cancelAnimationTimeout(node.rcAnimTimeout); + node.rcAnimTimeout = null; } - clearBrowserBugTimeout(node) + clearBrowserBugTimeout(node); - Event.removeEndEventListener(node, node.rcEndListener) - node.rcEndListener = null + Event.removeEndEventListener(node, node.rcEndListener); + node.rcEndListener = null; // Usually this optional callback is used for informing an owner of // a leave animation and telling it to remove the child. if (callback) { - callback() + callback(); } - } + }; - Event.addEndEventListener(node, node.rcEndListener) + Event.addEndEventListener(node, node.rcEndListener); node.rcAnimTimeout = requestAnimationTimeout(() => { for (const s in style) { if (style.hasOwnProperty(s)) { - node.style[s] = style[s] + node.style[s] = style[s]; } } - node.rcAnimTimeout = null - fixBrowserByTimeout(node) - }, 0) -} + node.rcAnimTimeout = null; + fixBrowserByTimeout(node); + }, 0); +}; cssAnimation.setTransition = (node, p, value) => { - let property = p - let v = value + let property = p; + let v = value; if (value === undefined) { - v = property - property = '' + v = property; + property = ''; } - property = property || '' - capitalPrefixes.forEach((prefix) => { - node.style[`${prefix}Transition${property}`] = v - }) -} + property = property || ''; + capitalPrefixes.forEach(prefix => { + node.style[`${prefix}Transition${property}`] = v; + }); +}; -cssAnimation.isCssAnimationSupported = isCssAnimationSupported +cssAnimation.isCssAnimationSupported = isCssAnimationSupported; -export { - isCssAnimationSupported, -} +export { isCssAnimationSupported }; -export default cssAnimation +export default cssAnimation; diff --git a/components/_util/env.js b/components/_util/env.js index 64365dbce..6a58df2b9 100644 --- a/components/_util/env.js +++ b/components/_util/env.js @@ -1,4 +1,4 @@ -export const inBrowser = typeof window !== 'undefined' -export const UA = inBrowser && window.navigator.userAgent.toLowerCase() -export const isIE = UA && /msie|trident/.test(UA) -export const isIE9 = UA && UA.indexOf('msie 9.0') > 0 +export const inBrowser = typeof window !== 'undefined'; +export const UA = inBrowser && window.navigator.userAgent.toLowerCase(); +export const isIE = UA && /msie|trident/.test(UA); +export const isIE9 = UA && UA.indexOf('msie 9.0') > 0; diff --git a/components/_util/getLocale.js b/components/_util/getLocale.js index ecd60b5cf..03aeca95b 100644 --- a/components/_util/getLocale.js +++ b/components/_util/getLocale.js @@ -1,30 +1,30 @@ -export function getComponentLocale (props, context, componentName, getDefaultLocale) { - let locale = {} +export function getComponentLocale(props, context, componentName, getDefaultLocale) { + let locale = {}; if (context && context.antLocale && context.antLocale[componentName]) { - locale = context.antLocale[componentName] + locale = context.antLocale[componentName]; } else { - const defaultLocale = getDefaultLocale() + const defaultLocale = getDefaultLocale(); // TODO: make default lang of antd be English // https://github.com/ant-design/ant-design/issues/6334 - locale = defaultLocale.default || defaultLocale + locale = defaultLocale.default || defaultLocale; } const result = { ...locale, ...props.locale, - } + }; result.lang = { ...locale.lang, ...props.locale.lang, - } - return result + }; + return result; } -export function getLocaleCode (context) { - const localeCode = context.antLocale && context.antLocale.locale +export function getLocaleCode(context) { + const localeCode = context.antLocale && context.antLocale.locale; // Had use LocaleProvide but didn't set locale if (context.antLocale && context.antLocale.exist && !localeCode) { - return 'zh-cn' + return 'zh-cn'; } - return localeCode + return localeCode; } diff --git a/components/_util/getRequestAnimationFrame.js b/components/_util/getRequestAnimationFrame.js index a4678dfef..2a6413e5b 100644 --- a/components/_util/getRequestAnimationFrame.js +++ b/components/_util/getRequestAnimationFrame.js @@ -1,44 +1,46 @@ -const availablePrefixs = ['moz', 'ms', 'webkit'] +const availablePrefixs = ['moz', 'ms', 'webkit']; -function requestAnimationFramePolyfill () { - let lastTime = 0 - return function (callback) { - const currTime = new Date().getTime() - const timeToCall = Math.max(0, 16 - (currTime - lastTime)) - const id = window.setTimeout(function () { callback(currTime + timeToCall) }, timeToCall) - lastTime = currTime + timeToCall - return id - } +function requestAnimationFramePolyfill() { + let lastTime = 0; + return function(callback) { + const currTime = new Date().getTime(); + const timeToCall = Math.max(0, 16 - (currTime - lastTime)); + const id = window.setTimeout(function() { + callback(currTime + timeToCall); + }, timeToCall); + lastTime = currTime + timeToCall; + return id; + }; } -export default function getRequestAnimationFrame () { +export default function getRequestAnimationFrame() { if (typeof window === 'undefined') { - return () => {} + return () => {}; } if (window.requestAnimationFrame) { // https://github.com/vuejs/vue/issues/4465 - return window.requestAnimationFrame.bind(window) + return window.requestAnimationFrame.bind(window); } - const prefix = availablePrefixs.filter(key => `${key}RequestAnimationFrame` in window)[0] + const prefix = availablePrefixs.filter(key => `${key}RequestAnimationFrame` in window)[0]; - return prefix - ? window[`${prefix}RequestAnimationFrame`] - : requestAnimationFramePolyfill() + return prefix ? window[`${prefix}RequestAnimationFrame`] : requestAnimationFramePolyfill(); } -export function cancelRequestAnimationFrame (id) { +export function cancelRequestAnimationFrame(id) { if (typeof window === 'undefined') { - return null + return null; } if (window.cancelAnimationFrame) { - return window.cancelAnimationFrame(id) + return window.cancelAnimationFrame(id); } - const prefix = availablePrefixs.filter(key => - `${key}CancelAnimationFrame` in window || `${key}CancelRequestAnimationFrame` in window, - )[0] + const prefix = availablePrefixs.filter( + key => `${key}CancelAnimationFrame` in window || `${key}CancelRequestAnimationFrame` in window, + )[0]; return prefix - ? (window[`${prefix}CancelAnimationFrame`] || window[`${prefix}CancelRequestAnimationFrame`]).call(this, id) - : clearTimeout(id) + ? ( + window[`${prefix}CancelAnimationFrame`] || window[`${prefix}CancelRequestAnimationFrame`] + ).call(this, id) + : clearTimeout(id); } diff --git a/components/_util/getScroll.js b/components/_util/getScroll.js index f600d7fed..1b085e3e3 100644 --- a/components/_util/getScroll.js +++ b/components/_util/getScroll.js @@ -1,17 +1,17 @@ -export default function getScroll (target, top) { +export default function getScroll(target, top) { if (typeof window === 'undefined') { - return 0 + return 0; } - const prop = top ? 'pageYOffset' : 'pageXOffset' - const method = top ? 'scrollTop' : 'scrollLeft' - const isWindow = target === window + const prop = top ? 'pageYOffset' : 'pageXOffset'; + const method = top ? 'scrollTop' : 'scrollLeft'; + const isWindow = target === window; - let ret = isWindow ? target[prop] : target[method] + let ret = isWindow ? target[prop] : target[method]; // ie6,7,8 standard mode if (isWindow && typeof ret !== 'number') { - ret = window.document.documentElement[method] + ret = window.document.documentElement[method]; } - return ret + return ret; } diff --git a/components/_util/getScrollBarSize.js b/components/_util/getScrollBarSize.js index 2573e1062..a98df563d 100644 --- a/components/_util/getScrollBarSize.js +++ b/components/_util/getScrollBarSize.js @@ -1,38 +1,38 @@ -let cached +let cached; -export default function getScrollBarSize (fresh) { +export default function getScrollBarSize(fresh) { if (fresh || cached === undefined) { - const inner = document.createElement('div') - inner.style.width = '100%' - inner.style.height = '200px' + const inner = document.createElement('div'); + inner.style.width = '100%'; + inner.style.height = '200px'; - const outer = document.createElement('div') - const outerStyle = outer.style + const outer = document.createElement('div'); + const outerStyle = outer.style; - outerStyle.position = 'absolute' - outerStyle.top = 0 - outerStyle.left = 0 - outerStyle.pointerEvents = 'none' - outerStyle.visibility = 'hidden' - outerStyle.width = '200px' - outerStyle.height = '150px' - outerStyle.overflow = 'hidden' + outerStyle.position = 'absolute'; + outerStyle.top = 0; + outerStyle.left = 0; + outerStyle.pointerEvents = 'none'; + outerStyle.visibility = 'hidden'; + outerStyle.width = '200px'; + outerStyle.height = '150px'; + outerStyle.overflow = 'hidden'; - outer.appendChild(inner) + outer.appendChild(inner); - document.body.appendChild(outer) + document.body.appendChild(outer); - const widthContained = inner.offsetWidth - outer.style.overflow = 'scroll' - let widthScroll = inner.offsetWidth + const widthContained = inner.offsetWidth; + outer.style.overflow = 'scroll'; + let widthScroll = inner.offsetWidth; if (widthContained === widthScroll) { - widthScroll = outer.clientWidth + widthScroll = outer.clientWidth; } - document.body.removeChild(outer) + document.body.removeChild(outer); - cached = widthContained - widthScroll + cached = widthContained - widthScroll; } - return cached + return cached; } diff --git a/components/_util/getTransitionProps.js b/components/_util/getTransitionProps.js index e450ced99..19d7a312a 100644 --- a/components/_util/getTransitionProps.js +++ b/components/_util/getTransitionProps.js @@ -1,7 +1,7 @@ -import animate from './css-animation' -const noop = () => {} +import animate from './css-animation'; +const noop = () => {}; const getTransitionProps = (transitionName, opt = {}) => { - const { beforeEnter, enter, afterEnter, leave, afterLeave, appear = true, tag } = opt + const { beforeEnter, enter, afterEnter, leave, afterLeave, appear = true, tag } = opt; const transitionProps = { props: { appear, @@ -9,21 +9,25 @@ const getTransitionProps = (transitionName, opt = {}) => { }, on: { beforeEnter: beforeEnter || noop, - enter: enter || ((el, done) => { - animate(el, `${transitionName}-enter`, done) - }), + enter: + enter || + ((el, done) => { + animate(el, `${transitionName}-enter`, done); + }), afterEnter: afterEnter || noop, - leave: leave || ((el, done) => { - animate(el, `${transitionName}-leave`, done) - }), + leave: + leave || + ((el, done) => { + animate(el, `${transitionName}-leave`, done); + }), afterLeave: afterLeave || noop, }, - } + }; // transition-group if (tag) { - transitionProps.tag = tag + transitionProps.tag = tag; } - return transitionProps -} + return transitionProps; +}; -export default getTransitionProps +export default getTransitionProps; diff --git a/components/_util/interopDefault.js b/components/_util/interopDefault.js index cb8fe3637..d1adc3c40 100644 --- a/components/_util/interopDefault.js +++ b/components/_util/interopDefault.js @@ -1,4 +1,4 @@ // https://github.com/moment/moment/issues/3650 -export default function interopDefault (m) { - return m.default || m +export default function interopDefault(m) { + return m.default || m; } diff --git a/components/_util/isCssAnimationSupported.js b/components/_util/isCssAnimationSupported.js index 791776cae..45d51bb35 100644 --- a/components/_util/isCssAnimationSupported.js +++ b/components/_util/isCssAnimationSupported.js @@ -1,24 +1,24 @@ -let animation +let animation; -function isCssAnimationSupported () { +function isCssAnimationSupported() { if (animation !== undefined) { - return animation + return animation; } - const domPrefixes = 'Webkit Moz O ms Khtml'.split(' ') - const elm = document.createElement('div') + const domPrefixes = 'Webkit Moz O ms Khtml'.split(' '); + const elm = document.createElement('div'); if (elm.style.animationName !== undefined) { - animation = true + animation = true; } if (animation !== undefined) { for (let i = 0; i < domPrefixes.length; i++) { if (elm.style[`${domPrefixes[i]}AnimationName`] !== undefined) { - animation = true - break + animation = true; + break; } } } - animation = animation || false - return animation + animation = animation || false; + return animation; } -export default isCssAnimationSupported +export default isCssAnimationSupported; diff --git a/components/_util/isFlexSupported.js b/components/_util/isFlexSupported.js index d9d8a8887..dd6a5ae7e 100644 --- a/components/_util/isFlexSupported.js +++ b/components/_util/isFlexSupported.js @@ -1,10 +1,12 @@ -export default function isFlexSupported () { +export default function isFlexSupported() { if (typeof window !== 'undefined' && window.document && window.document.documentElement) { - const { documentElement } = window.document - return 'flex' in documentElement.style || + const { documentElement } = window.document; + return ( + 'flex' in documentElement.style || 'webkitFlex' in documentElement.style || 'Flex' in documentElement.style || 'msFlex' in documentElement.style + ); } - return false + return false; } diff --git a/components/_util/isNumeric.js b/components/_util/isNumeric.js index d29361315..cfe09479b 100644 --- a/components/_util/isNumeric.js +++ b/components/_util/isNumeric.js @@ -1,4 +1,4 @@ -const isNumeric = (value) => { - return !isNaN(parseFloat(value)) && isFinite(value) -} -export default isNumeric +const isNumeric = value => { + return !isNaN(parseFloat(value)) && isFinite(value); +}; +export default isNumeric; diff --git a/components/_util/openAnimation.js b/components/_util/openAnimation.js index 23a07ff7f..05c82c4fc 100644 --- a/components/_util/openAnimation.js +++ b/components/_util/openAnimation.js @@ -1,64 +1,64 @@ -import cssAnimation from './css-animation' -import raf from 'raf' +import cssAnimation from './css-animation'; +import raf from 'raf'; -function animate (node, show, done, type) { - let height - let requestAnimationFrameId - let appearRequestAnimationFrameId +function animate(node, show, done, type) { + let height; + let requestAnimationFrameId; + let appearRequestAnimationFrameId; return cssAnimation(node, 'ant-motion-collapse', { - start () { + start() { if (appearRequestAnimationFrameId) { - raf.cancel(appearRequestAnimationFrameId) + raf.cancel(appearRequestAnimationFrameId); } if (!show) { - node.style.height = `${node.offsetHeight}px` - node.style.opacity = '1' + node.style.height = `${node.offsetHeight}px`; + node.style.opacity = '1'; } else { - height = node.offsetHeight + height = node.offsetHeight; // not get offsetHeight when appear // set it into raf get correct offsetHeight if (height === 0) { appearRequestAnimationFrameId = raf(() => { - height = node.offsetHeight - node.style.height = '0px' - node.style.opacity = '0' - }) + height = node.offsetHeight; + node.style.height = '0px'; + node.style.opacity = '0'; + }); } else { - node.style.height = '0px' - node.style.opacity = '0' + node.style.height = '0px'; + node.style.opacity = '0'; } } }, - active () { + active() { if (requestAnimationFrameId) { - raf.cancel(requestAnimationFrameId) + raf.cancel(requestAnimationFrameId); } requestAnimationFrameId = raf(() => { - node.style.height = `${show ? height : 0}px` - node.style.opacity = show ? '1' : '0' - }) + node.style.height = `${show ? height : 0}px`; + node.style.opacity = show ? '1' : '0'; + }); }, - end () { + end() { if (appearRequestAnimationFrameId) { - raf.cancel(appearRequestAnimationFrameId) + raf.cancel(appearRequestAnimationFrameId); } if (requestAnimationFrameId) { - raf.cancel(requestAnimationFrameId) + raf.cancel(requestAnimationFrameId); } - node.style.height = '' - node.style.opacity = '' - done && done() + node.style.height = ''; + node.style.opacity = ''; + done && done(); }, - }) + }); } const animation = { - enter (node, done) { - return animate(node, true, done) + enter(node, done) { + return animate(node, true, done); }, - leave (node, done) { - return animate(node, false, done) + leave(node, done) { + return animate(node, false, done); }, -} +}; -export default animation +export default animation; diff --git a/components/_util/props-util.js b/components/_util/props-util.js index 65856cae9..a977c9e19 100644 --- a/components/_util/props-util.js +++ b/components/_util/props-util.js @@ -1,264 +1,276 @@ -import isPlainObject from 'lodash/isPlainObject' -import classNames from 'classnames' -function getType (fn) { - const match = fn && fn.toString().match(/^\s*function (\w+)/) - return match ? match[1] : '' +import isPlainObject from 'lodash/isPlainObject'; +import classNames from 'classnames'; +function getType(fn) { + const match = fn && fn.toString().match(/^\s*function (\w+)/); + return match ? match[1] : ''; } -const camelizeRE = /-(\w)/g -const camelize = (str) => { - return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '') -} +const camelizeRE = /-(\w)/g; +const camelize = str => { + return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : '')); +}; const parseStyleText = (cssText = '', camel) => { - const res = {} - const listDelimiter = /;(?![^(]*\))/g - const propertyDelimiter = /:(.+)/ - cssText.split(listDelimiter).forEach(function (item) { + const res = {}; + const listDelimiter = /;(?![^(]*\))/g; + const propertyDelimiter = /:(.+)/; + cssText.split(listDelimiter).forEach(function(item) { if (item) { - const tmp = item.split(propertyDelimiter) + const tmp = item.split(propertyDelimiter); if (tmp.length > 1) { - const k = camel ? camelize(tmp[0].trim()) : tmp[0].trim() - res[k] = tmp[1].trim() + const k = camel ? camelize(tmp[0].trim()) : tmp[0].trim(); + res[k] = tmp[1].trim(); } } - }) - return res -} + }); + return res; +}; const hasProp = (instance, prop) => { - const $options = instance.$options || {} - const propsData = $options.propsData || {} - return prop in propsData -} + const $options = instance.$options || {}; + const propsData = $options.propsData || {}; + return prop in propsData; +}; const slotHasProp = (slot, prop) => { - const $options = slot.componentOptions || {} - const propsData = $options.propsData || {} - return prop in propsData -} + const $options = slot.componentOptions || {}; + const propsData = $options.propsData || {}; + return prop in propsData; +}; const filterProps = (props, propsData = {}) => { - const res = {} - Object.keys(props).forEach((k) => { + const res = {}; + Object.keys(props).forEach(k => { if (k in propsData || props[k] !== undefined) { - res[k] = props[k] + res[k] = props[k]; } - }) - return res -} -const getSlots = (ele) => { - let componentOptions = ele.componentOptions || {} + }); + return res; +}; +const getSlots = ele => { + let componentOptions = ele.componentOptions || {}; if (ele.$vnode) { - componentOptions = ele.$vnode.componentOptions || {} + componentOptions = ele.$vnode.componentOptions || {}; } - const children = ele.children || componentOptions.children || [] - const slots = {} + const children = ele.children || componentOptions.children || []; + const slots = {}; children.forEach(child => { if (!isEmptyElement(child)) { - const name = (child.data && child.data.slot) || 'default' - slots[name] = slots[name] || [] - slots[name].push(child) + const name = (child.data && child.data.slot) || 'default'; + slots[name] = slots[name] || []; + slots[name].push(child); } - }) - return slots -} -const getAllChildren = (ele) => { - let componentOptions = ele.componentOptions || {} + }); + return slots; +}; +const getAllChildren = ele => { + let componentOptions = ele.componentOptions || {}; if (ele.$vnode) { - componentOptions = ele.$vnode.componentOptions || {} + componentOptions = ele.$vnode.componentOptions || {}; } - return ele.children || componentOptions.children || [] -} -const getSlotOptions = (ele) => { - if (ele.fnOptions) { // 函数式组件 - return ele.fnOptions + return ele.children || componentOptions.children || []; +}; +const getSlotOptions = ele => { + if (ele.fnOptions) { + // 函数式组件 + return ele.fnOptions; } - let componentOptions = ele.componentOptions + let componentOptions = ele.componentOptions; if (ele.$vnode) { - componentOptions = ele.$vnode.componentOptions + componentOptions = ele.$vnode.componentOptions; } - return componentOptions ? componentOptions.Ctor.options || {} : {} -} -const getOptionProps = (instance) => { + return componentOptions ? componentOptions.Ctor.options || {} : {}; +}; +const getOptionProps = instance => { if (instance.componentOptions) { - const componentOptions = instance.componentOptions - const { propsData = {}, Ctor = {}} = componentOptions - const props = (Ctor.options || {}).props || {} - const res = {} + const componentOptions = instance.componentOptions; + const { propsData = {}, Ctor = {} } = componentOptions; + const props = (Ctor.options || {}).props || {}; + const res = {}; for (const [k, v] of Object.entries(props)) { - const def = v.default + const def = v.default; if (def !== undefined) { - res[k] = typeof def === 'function' && getType(v.type) !== 'Function' - ? def.call(instance) - : def + res[k] = + typeof def === 'function' && getType(v.type) !== 'Function' ? def.call(instance) : def; } } - return { ...res, ...propsData } + return { ...res, ...propsData }; } - const { $options = {}, $props = {}} = instance - return filterProps($props, $options.propsData) -} + const { $options = {}, $props = {} } = instance; + return filterProps($props, $options.propsData); +}; const getComponentFromProp = (instance, prop, options = instance, execute = true) => { if (instance.$createElement) { - const h = instance.$createElement - const temp = instance[prop] + const h = instance.$createElement; + const temp = instance[prop]; if (temp !== undefined) { - return typeof temp === 'function' && execute ? temp(h, options) : temp + return typeof temp === 'function' && execute ? temp(h, options) : temp; } - return instance.$slots[prop] || - (instance.$scopedSlots[prop] && execute && instance.$scopedSlots[prop](options)) || - (instance.$scopedSlots[prop] && instance.$scopedSlots[prop]) || - undefined + return ( + instance.$slots[prop] || + (instance.$scopedSlots[prop] && execute && instance.$scopedSlots[prop](options)) || + instance.$scopedSlots[prop] || + undefined + ); } else { - const h = instance.context.$createElement - const temp = getPropsData(instance)[prop] + const h = instance.context.$createElement; + const temp = getPropsData(instance)[prop]; if (temp !== undefined) { - return typeof temp === 'function' && execute ? temp(h, options) : temp + return typeof temp === 'function' && execute ? temp(h, options) : temp; } - const slotsProp = [] + const slotsProp = []; const componentOptions = instance.componentOptions || {}; - (componentOptions.children || []).forEach((child) => { + (componentOptions.children || []).forEach(child => { if (child.data && child.data.slot === prop) { if (child.tag === 'template') { - slotsProp.push(child.children) + slotsProp.push(child.children); } else { - slotsProp.push(child) + slotsProp.push(child); } } - }) - return slotsProp.length ? slotsProp : undefined + }); + return slotsProp.length ? slotsProp : undefined; } -} +}; -const getAllProps = (ele) => { - let data = ele.data || {} - let componentOptions = ele.componentOptions || {} +const getAllProps = ele => { + let data = ele.data || {}; + let componentOptions = ele.componentOptions || {}; if (ele.$vnode) { - data = ele.$vnode.data || {} - componentOptions = ele.$vnode.componentOptions || {} + data = ele.$vnode.data || {}; + componentOptions = ele.$vnode.componentOptions || {}; } - return { ...data.props, ...data.attrs, ...componentOptions.propsData } -} + return { ...data.props, ...data.attrs, ...componentOptions.propsData }; +}; -const getPropsData = (ele) => { - let componentOptions = ele.componentOptions +const getPropsData = ele => { + let componentOptions = ele.componentOptions; if (ele.$vnode) { - componentOptions = ele.$vnode.componentOptions + componentOptions = ele.$vnode.componentOptions; } - return componentOptions ? componentOptions.propsData || {} : {} -} + return componentOptions ? componentOptions.propsData || {} : {}; +}; const getValueByProp = (ele, prop) => { - return getPropsData(ele)[prop] -} + return getPropsData(ele)[prop]; +}; -const getAttrs = (ele) => { - let data = ele.data +const getAttrs = ele => { + let data = ele.data; if (ele.$vnode) { - data = ele.$vnode.data + data = ele.$vnode.data; } - return data ? data.attrs || {} : {} -} + return data ? data.attrs || {} : {}; +}; -const getKey = (ele) => { - let key = ele.key +const getKey = ele => { + let key = ele.key; if (ele.$vnode) { - key = ele.$vnode.key + key = ele.$vnode.key; } - return key -} + return key; +}; -export function getEvents (child) { - let events = {} +export function getEvents(child) { + let events = {}; if (child.componentOptions && child.componentOptions.listeners) { - events = child.componentOptions.listeners + events = child.componentOptions.listeners; } else if (child.data && child.data.on) { - events = child.data.on + events = child.data.on; } - return { ...events } + return { ...events }; } -export function getClass (ele) { - let data = {} +export function getClass(ele) { + let data = {}; if (ele.data) { - data = ele.data + data = ele.data; } else if (ele.$vnode && ele.$vnode.data) { - data = ele.$vnode.data + data = ele.$vnode.data; } - const tempCls = data.class || {} - const staticClass = data.staticClass - let cls = {} - staticClass && staticClass.split(' ').forEach(c => { cls[c.trim()] = true }) + const tempCls = data.class || {}; + const staticClass = data.staticClass; + let cls = {}; + staticClass && + staticClass.split(' ').forEach(c => { + cls[c.trim()] = true; + }); if (typeof tempCls === 'string') { - tempCls.split(' ').forEach(c => { cls[c.trim()] = true }) + tempCls.split(' ').forEach(c => { + cls[c.trim()] = true; + }); } else if (Array.isArray(tempCls)) { - classNames(tempCls).split(' ').forEach(c => { cls[c.trim()] = true }) + classNames(tempCls) + .split(' ') + .forEach(c => { + cls[c.trim()] = true; + }); } else { - cls = { ...cls, ...tempCls } + cls = { ...cls, ...tempCls }; } - return cls + return cls; } -export function getStyle (ele, camel) { - let data = {} +export function getStyle(ele, camel) { + let data = {}; if (ele.data) { - data = ele.data + data = ele.data; } else if (ele.$vnode && ele.$vnode.data) { - data = ele.$vnode.data + data = ele.$vnode.data; } - let style = data.style || data.staticStyle + let style = data.style || data.staticStyle; if (typeof style === 'string') { - style = parseStyleText(style, camel) - } else if (camel && style) { // 驼峰化 - const res = {} - Object.keys(style).forEach(k => (res[camelize(k)] = style[k])) - return res + style = parseStyleText(style, camel); + } else if (camel && style) { + // 驼峰化 + const res = {}; + Object.keys(style).forEach(k => (res[camelize(k)] = style[k])); + return res; } - return style + return style; } -export function getComponentName (opts) { - return opts && (opts.Ctor.options.name || opts.tag) +export function getComponentName(opts) { + return opts && (opts.Ctor.options.name || opts.tag); } -export function isEmptyElement (c) { - return !(c.tag || (c.text && c.text.trim() !== '')) +export function isEmptyElement(c) { + return !(c.tag || (c.text && c.text.trim() !== '')); } -export function filterEmpty (children = []) { - return children.filter(c => !isEmptyElement(c)) +export function filterEmpty(children = []) { + return children.filter(c => !isEmptyElement(c)); } const initDefaultProps = (propTypes, defaultProps) => { Object.keys(defaultProps).forEach(k => { if (propTypes[k]) { - propTypes[k].def && (propTypes[k] = propTypes[k].def(defaultProps[k])) + propTypes[k].def && (propTypes[k] = propTypes[k].def(defaultProps[k])); } else { - throw new Error( - `not have ${k} prop`, - ) + throw new Error(`not have ${k} prop`); } - }) - return propTypes -} + }); + return propTypes; +}; -export function mergeProps () { - const args = [].slice.call(arguments, 0) - const props = {} +export function mergeProps() { + const args = [].slice.call(arguments, 0); + const props = {}; args.forEach((p = {}, i) => { for (const [k, v] of Object.entries(p)) { - props[k] = props[k] || {} + props[k] = props[k] || {}; if (isPlainObject(v)) { - Object.assign(props[k], v) + Object.assign(props[k], v); } else { - props[k] = v + props[k] = v; } } - }) - return props + }); + return props; } -function isValidElement (element) { - return element && +function isValidElement(element) { + return ( + element && typeof element === 'object' && 'componentOptions' in element && 'context' in element && - element.tag !== undefined // remove text node + element.tag !== undefined + ); // remove text node } export { @@ -279,5 +291,5 @@ export { getSlots, getAllProps, getAllChildren, -} -export default hasProp +}; +export default hasProp; diff --git a/components/_util/proxyComponent.jsx b/components/_util/proxyComponent.jsx index b913c5037..db1e8b3dc 100644 --- a/components/_util/proxyComponent.jsx +++ b/components/_util/proxyComponent.jsx @@ -1,29 +1,30 @@ +import PropTypes from './vue-types'; +import { getOptionProps } from './props-util'; -import PropTypes from './vue-types' -import { getOptionProps } from './props-util' - -function getDisplayName (WrappedComponent) { - return WrappedComponent.name || 'Component' +function getDisplayName(WrappedComponent) { + return WrappedComponent.name || 'Component'; } -export default function wrapWithConnect (WrappedComponent) { - const tempProps = WrappedComponent.props || {} - const methods = WrappedComponent.methods || {} - const props = {} - Object.keys(tempProps).forEach(k => { props[k] = ({ ...k, required: false }) }) - WrappedComponent.props.__propsSymbol__ = PropTypes.any - WrappedComponent.props.children = PropTypes.array.def([]) +export default function wrapWithConnect(WrappedComponent) { + const tempProps = WrappedComponent.props || {}; + const methods = WrappedComponent.methods || {}; + const props = {}; + Object.keys(tempProps).forEach(k => { + props[k] = { ...k, required: false }; + }); + WrappedComponent.props.__propsSymbol__ = PropTypes.any; + WrappedComponent.props.children = PropTypes.array.def([]); const ProxyWrappedComponent = { props, model: WrappedComponent.model, name: `Proxy_${getDisplayName(WrappedComponent)}`, methods: { - getProxyWrappedInstance () { - return this.$refs.wrappedInstance + getProxyWrappedInstance() { + return this.$refs.wrappedInstance; }, }, - render () { - const { $listeners, $slots = {}, $attrs, $scopedSlots } = this - const props = getOptionProps(this) + render() { + const { $listeners, $slots = {}, $attrs, $scopedSlots } = this; + const props = getOptionProps(this); const wrapProps = { props: { ...props, @@ -33,24 +34,26 @@ export default function wrapWithConnect (WrappedComponent) { }, on: $listeners, attrs: $attrs, - } + }; if (Object.keys($scopedSlots).length) { - wrapProps.scopedSlots = $scopedSlots + wrapProps.scopedSlots = $scopedSlots; } - const slotsKey = Object.keys($slots) + const slotsKey = Object.keys($slots); return ( - - {slotsKey.length ? slotsKey.map(name => { - return - }) : null} + + {slotsKey.length + ? slotsKey.map(name => { + return ; + }) + : null} - ) + ); }, - } + }; Object.keys(methods).map(m => { - ProxyWrappedComponent.methods[m] = function () { - return this.getProxyWrappedInstance()[m](...arguments) - } - }) - return ProxyWrappedComponent + ProxyWrappedComponent.methods[m] = function() { + return this.getProxyWrappedInstance()[m](...arguments); + }; + }); + return ProxyWrappedComponent; } diff --git a/components/_util/raf.js b/components/_util/raf.js index ef632d25b..f9108cb14 100644 --- a/components/_util/raf.js +++ b/components/_util/raf.js @@ -1,30 +1,30 @@ -import raf from 'raf' +import raf from 'raf'; -let id = 0 -const ids = {} +let id = 0; +const ids = {}; // Support call raf with delay specified frame -export default function wrapperRaf (callback, delayFrames = 1) { - const myId = id++ - let restFrames = delayFrames +export default function wrapperRaf(callback, delayFrames = 1) { + const myId = id++; + let restFrames = delayFrames; - function internalCallback () { - restFrames -= 1 + function internalCallback() { + restFrames -= 1; if (restFrames <= 0) { - callback() - delete ids[id] + callback(); + delete ids[id]; } else { - ids[id] = raf(internalCallback) + ids[id] = raf(internalCallback); } } - ids[id] = raf(internalCallback) + ids[id] = raf(internalCallback); - return myId + return myId; } -wrapperRaf.cancel = function (id) { - raf.cancel(ids[id]) - delete ids[id] -} +wrapperRaf.cancel = function(id) { + raf.cancel(ids[id]); + delete ids[id]; +}; diff --git a/components/_util/requestAnimationTimeout.js b/components/_util/requestAnimationTimeout.js index ee3720fe8..beae9ea29 100644 --- a/components/_util/requestAnimationTimeout.js +++ b/components/_util/requestAnimationTimeout.js @@ -1,22 +1,23 @@ +import getRequestAnimationFrame, { + cancelRequestAnimationFrame as caf, +} from './getRequestAnimationFrame'; +const raf = getRequestAnimationFrame(); -import getRequestAnimationFrame, { cancelRequestAnimationFrame as caf } from './getRequestAnimationFrame' -const raf = getRequestAnimationFrame() - -export const cancelAnimationTimeout = (frame) => caf(frame.id) +export const cancelAnimationTimeout = frame => caf(frame.id); export const requestAnimationTimeout = (callback, delay) => { - const start = Date.now() - function timeout () { + const start = Date.now(); + function timeout() { if (Date.now() - start >= delay) { - callback.call() + callback.call(); } else { - frame.id = raf(timeout) + frame.id = raf(timeout); } } const frame = { id: raf(timeout), - } + }; - return frame -} + return frame; +}; diff --git a/components/_util/store/PropTypes.js b/components/_util/store/PropTypes.js index 603ffe6bb..b18a10128 100644 --- a/components/_util/store/PropTypes.js +++ b/components/_util/store/PropTypes.js @@ -1,7 +1,7 @@ -import PropTypes from '../vue-types' +import PropTypes from '../vue-types'; export const storeShape = PropTypes.shape({ subscribe: PropTypes.func.isRequired, setState: PropTypes.func.isRequired, getState: PropTypes.func.isRequired, -}) +}); diff --git a/components/_util/store/Provider.jsx b/components/_util/store/Provider.jsx index cdf97b99f..c8f3148a2 100644 --- a/components/_util/store/Provider.jsx +++ b/components/_util/store/Provider.jsx @@ -1,16 +1,15 @@ - -import { storeShape } from './PropTypes' +import { storeShape } from './PropTypes'; export default { name: 'StoreProvider', props: { store: storeShape.isRequired, }, - provide () { + provide() { return { storeContext: this.$props, - } + }; }, - render () { - return this.$slots.default[0] + render() { + return this.$slots.default[0]; }, -} +}; diff --git a/components/_util/store/connect.jsx b/components/_util/store/connect.jsx index dd9fe924e..418a5af66 100644 --- a/components/_util/store/connect.jsx +++ b/components/_util/store/connect.jsx @@ -1,84 +1,89 @@ -import shallowEqual from 'shallowequal' -import omit from 'omit.js' -import { getOptionProps } from '../props-util' -import PropTypes from '../vue-types' -import proxyComponent from '../proxyComponent' +import shallowEqual from 'shallowequal'; +import omit from 'omit.js'; +import { getOptionProps } from '../props-util'; +import PropTypes from '../vue-types'; +import proxyComponent from '../proxyComponent'; -function getDisplayName (WrappedComponent) { - return WrappedComponent.name || 'Component' +function getDisplayName(WrappedComponent) { + return WrappedComponent.name || 'Component'; } -const defaultMapStateToProps = () => ({}) -export default function connect (mapStateToProps) { - const shouldSubscribe = !!mapStateToProps - const finnalMapStateToProps = mapStateToProps || defaultMapStateToProps - return function wrapWithConnect (WrappedComponent) { - const tempProps = omit(WrappedComponent.props || {}, ['store']) +const defaultMapStateToProps = () => ({}); +export default function connect(mapStateToProps) { + const shouldSubscribe = !!mapStateToProps; + const finnalMapStateToProps = mapStateToProps || defaultMapStateToProps; + return function wrapWithConnect(WrappedComponent) { + const tempProps = omit(WrappedComponent.props || {}, ['store']); const props = { __propsSymbol__: PropTypes.any, - } - Object.keys(tempProps).forEach(k => { props[k] = ({ ...k, required: false }) }) + }; + Object.keys(tempProps).forEach(k => { + props[k] = { ...k, required: false }; + }); const Connect = { name: `Connect_${getDisplayName(WrappedComponent)}`, props, inject: { - storeContext: { default: {}}, + storeContext: { default: {} }, }, - data () { - this.store = this.storeContext.store - this.preProps = omit(getOptionProps(this), ['__propsSymbol__']) + data() { + this.store = this.storeContext.store; + this.preProps = omit(getOptionProps(this), ['__propsSymbol__']); return { subscribed: finnalMapStateToProps(this.store.getState(), this.$props), - } + }; }, watch: { - __propsSymbol__ () { + __propsSymbol__() { if (mapStateToProps && mapStateToProps.length === 2) { - this.subscribed = finnalMapStateToProps(this.store.getState(), this.$props) + this.subscribed = finnalMapStateToProps(this.store.getState(), this.$props); } }, }, - mounted () { - this.trySubscribe() + mounted() { + this.trySubscribe(); }, - beforeDestroy () { - this.tryUnsubscribe() + beforeDestroy() { + this.tryUnsubscribe(); }, methods: { - handleChange () { + handleChange() { if (!this.unsubscribe) { - return + return; } - const props = omit(getOptionProps(this), ['__propsSymbol__']) - const nextSubscribed = finnalMapStateToProps(this.store.getState(), props) - if (!shallowEqual(this.preProps, props) || !shallowEqual(this.subscribed, nextSubscribed)) { - this.subscribed = nextSubscribed + const props = omit(getOptionProps(this), ['__propsSymbol__']); + const nextSubscribed = finnalMapStateToProps(this.store.getState(), props); + if ( + !shallowEqual(this.preProps, props) || + !shallowEqual(this.subscribed, nextSubscribed) + ) { + this.subscribed = nextSubscribed; } }, - trySubscribe () { + trySubscribe() { if (shouldSubscribe) { - this.unsubscribe = this.store.subscribe(this.handleChange) - this.handleChange() + this.unsubscribe = this.store.subscribe(this.handleChange); + this.handleChange(); } }, - tryUnsubscribe () { + tryUnsubscribe() { if (this.unsubscribe) { - this.unsubscribe() - this.unsubscribe = null + this.unsubscribe(); + this.unsubscribe = null; } }, - getWrappedInstance () { - return this.$refs.wrappedInstance + getWrappedInstance() { + return this.$refs.wrappedInstance; }, }, - render () { - this.preProps = { ...this.$props } - const { $listeners, $slots = {}, $attrs, $scopedSlots, subscribed, store } = this - const props = getOptionProps(this) - this.preProps = { ...omit(props, ['__propsSymbol__']) } + render() { + this.preProps = { ...this.$props }; + const { $listeners, $slots = {}, $attrs, $scopedSlots, subscribed, store } = this; + const props = getOptionProps(this); + this.preProps = { ...omit(props, ['__propsSymbol__']) }; const wrapProps = { props: { ...props, @@ -88,16 +93,16 @@ export default function connect (mapStateToProps) { on: $listeners, attrs: $attrs, scopedSlots: $scopedSlots, - } + }; return ( - + {Object.keys($slots).map(name => { - return + return ; })} - ) + ); }, - } - return proxyComponent(Connect) - } + }; + return proxyComponent(Connect); + }; } diff --git a/components/_util/store/create.js b/components/_util/store/create.js index 57ce3e083..6fc0e1ae0 100644 --- a/components/_util/store/create.js +++ b/components/_util/store/create.js @@ -1,30 +1,30 @@ -export default function create (initialState) { - let state = initialState - const listeners = [] +export default function create(initialState) { + let state = initialState; + const listeners = []; - function setState (partial) { - state = { ...state, ...partial } + function setState(partial) { + state = { ...state, ...partial }; for (let i = 0; i < listeners.length; i++) { - listeners[i]() + listeners[i](); } } - function getState () { - return state + function getState() { + return state; } - function subscribe (listener) { - listeners.push(listener) + function subscribe(listener) { + listeners.push(listener); - return function unsubscribe () { - const index = listeners.indexOf(listener) - listeners.splice(index, 1) - } + return function unsubscribe() { + const index = listeners.indexOf(listener); + listeners.splice(index, 1); + }; } return { setState, getState, subscribe, - } + }; } diff --git a/components/_util/store/index.js b/components/_util/store/index.js index 62d58a9a3..9b0e3733d 100644 --- a/components/_util/store/index.js +++ b/components/_util/store/index.js @@ -1,5 +1,5 @@ -export { default as Provider } from './Provider' +export { default as Provider } from './Provider'; -export { default as connect } from './connect' +export { default as connect } from './connect'; -export { default as create } from './create' +export { default as create } from './create'; diff --git a/components/_util/throttleByAnimationFrame.js b/components/_util/throttleByAnimationFrame.js index 15d5a86fc..6bd328542 100644 --- a/components/_util/throttleByAnimationFrame.js +++ b/components/_util/throttleByAnimationFrame.js @@ -1,45 +1,45 @@ -import raf from 'raf' +import raf from 'raf'; -export default function throttleByAnimationFrame (fn) { - let requestId +export default function throttleByAnimationFrame(fn) { + let requestId; const later = args => () => { - requestId = null - fn(...args) - } + requestId = null; + fn(...args); + }; const throttled = (...args) => { if (requestId == null) { - requestId = raf(later(args)) + requestId = raf(later(args)); } - } + }; - throttled.cancel = () => raf.cancel(requestId) + throttled.cancel = () => raf.cancel(requestId); - return throttled + return throttled; } -export function throttleByAnimationFrameDecorator () { - return function (target, key, descriptor) { - const fn = descriptor.value - let definingProperty = false +export function throttleByAnimationFrameDecorator() { + return function(target, key, descriptor) { + const fn = descriptor.value; + let definingProperty = false; return { configurable: true, - get () { + get() { if (definingProperty || this === target.prototype || this.hasOwnProperty(key)) { - return fn + return fn; } - const boundFn = throttleByAnimationFrame(fn.bind(this)) - definingProperty = true + const boundFn = throttleByAnimationFrame(fn.bind(this)); + definingProperty = true; Object.defineProperty(this, key, { value: boundFn, configurable: true, writable: true, - }) - definingProperty = false - return boundFn + }); + definingProperty = false; + return boundFn; }, - } - } + }; + }; } diff --git a/components/_util/triggerEvent.js b/components/_util/triggerEvent.js index bca06148f..40b37473d 100644 --- a/components/_util/triggerEvent.js +++ b/components/_util/triggerEvent.js @@ -1,8 +1,8 @@ -export default function triggerEvent (el, type) { +export default function triggerEvent(el, type) { if ('createEvent' in document) { // modern browsers, IE9+ - const e = document.createEvent('HTMLEvents') - e.initEvent(type, false, true) - el.dispatchEvent(e) + const e = document.createEvent('HTMLEvents'); + e.initEvent(type, false, true); + el.dispatchEvent(e); } } diff --git a/components/_util/vnode.js b/components/_util/vnode.js index 7d5e01603..4ca58202d 100644 --- a/components/_util/vnode.js +++ b/components/_util/vnode.js @@ -1,16 +1,16 @@ -import { filterEmpty, parseStyleText } from './props-util' -export function cloneVNode (vnode, deep) { - const componentOptions = vnode.componentOptions - const data = vnode.data +import { filterEmpty, parseStyleText } from './props-util'; +export function cloneVNode(vnode, deep) { + const componentOptions = vnode.componentOptions; + const data = vnode.data; - let listeners = {} + let listeners = {}; if (componentOptions && componentOptions.listeners) { - listeners = { ...componentOptions.listeners } + listeners = { ...componentOptions.listeners }; } - let on = {} + let on = {}; if (data && data.on) { - on = { ...data.on } + on = { ...data.on }; } const cloned = new vnode.constructor( @@ -21,49 +21,49 @@ export function cloneVNode (vnode, deep) { vnode.elm, vnode.context, componentOptions ? { ...componentOptions, listeners } : componentOptions, - vnode.asyncFactory - ) - cloned.ns = vnode.ns - cloned.isStatic = vnode.isStatic - cloned.key = vnode.key - cloned.isComment = vnode.isComment - cloned.fnContext = vnode.fnContext - cloned.fnOptions = vnode.fnOptions - cloned.fnScopeId = vnode.fnScopeId - cloned.isCloned = true + vnode.asyncFactory, + ); + cloned.ns = vnode.ns; + cloned.isStatic = vnode.isStatic; + cloned.key = vnode.key; + cloned.isComment = vnode.isComment; + cloned.fnContext = vnode.fnContext; + cloned.fnOptions = vnode.fnOptions; + cloned.fnScopeId = vnode.fnScopeId; + cloned.isCloned = true; if (deep) { if (vnode.children) { - cloned.children = cloneVNodes(vnode.children, true) + cloned.children = cloneVNodes(vnode.children, true); } if (componentOptions && componentOptions.children) { - componentOptions.children = cloneVNodes(componentOptions.children, true) + componentOptions.children = cloneVNodes(componentOptions.children, true); } } - return cloned + return cloned; } -export function cloneVNodes (vnodes, deep) { - const len = vnodes.length - const res = new Array(len) +export function cloneVNodes(vnodes, deep) { + const len = vnodes.length; + const res = new Array(len); for (let i = 0; i < len; i++) { - res[i] = cloneVNode(vnodes[i], deep) + res[i] = cloneVNode(vnodes[i], deep); } - return res + return res; } -export function cloneElement (n, nodeProps = {}, deep) { - let ele = n +export function cloneElement(n, nodeProps = {}, deep) { + let ele = n; if (Array.isArray(n)) { - ele = filterEmpty(n)[0] + ele = filterEmpty(n)[0]; } if (!ele) { - return null + return null; } - const node = cloneVNode(ele, deep) - const { props = {}, key, on = {}, children, directives = [] } = nodeProps - const data = node.data || {} - let cls = {} - let style = {} + const node = cloneVNode(ele, deep); + const { props = {}, key, on = {}, children, directives = [] } = nodeProps; + const data = node.data || {}; + let cls = {}; + let style = {}; const { attrs = {}, ref, @@ -71,28 +71,32 @@ export function cloneElement (n, nodeProps = {}, deep) { style: tempStyle = {}, class: tempCls = {}, scopedSlots = {}, - } = nodeProps + } = nodeProps; if (typeof data.style === 'string') { - style = parseStyleText(data.style) + style = parseStyleText(data.style); } else { - style = { ...data.style, ...style } + style = { ...data.style, ...style }; } if (typeof tempStyle === 'string') { - style = { ...style, ...parseStyleText(style) } + style = { ...style, ...parseStyleText(style) }; } else { - style = { ...style, ...tempStyle } + style = { ...style, ...tempStyle }; } if (typeof data.class === 'string' && data.class.trim() !== '') { - data.class.split(' ').forEach(c => { cls[c.trim()] = true }) + data.class.split(' ').forEach(c => { + cls[c.trim()] = true; + }); } else { - cls = { ...data.class, ...cls } + cls = { ...data.class, ...cls }; } if (typeof tempCls === 'string' && tempCls.trim() !== '') { - tempCls.split(' ').forEach(c => { cls[c.trim()] = true }) + tempCls.split(' ').forEach(c => { + cls[c.trim()] = true; + }); } else { - cls = { ...cls, ...tempCls } + cls = { ...cls, ...tempCls }; } node.data = Object.assign({}, data, { style, @@ -101,27 +105,26 @@ export function cloneElement (n, nodeProps = {}, deep) { domProps: { ...data.domProps, ...domProps }, scopedSlots: { ...data.scopedSlots, ...scopedSlots }, directives: [...(data.directives || []), ...directives], - }) + }); if (node.componentOptions) { - node.componentOptions.propsData = node.componentOptions.propsData || {} - node.componentOptions.listeners = node.componentOptions.listeners || {} - node.componentOptions.propsData = { ...node.componentOptions.propsData, ...props } - node.componentOptions.listeners = { ...node.componentOptions.listeners, ...on } + node.componentOptions.propsData = node.componentOptions.propsData || {}; + node.componentOptions.listeners = node.componentOptions.listeners || {}; + node.componentOptions.propsData = { ...node.componentOptions.propsData, ...props }; + node.componentOptions.listeners = { ...node.componentOptions.listeners, ...on }; if (children) { - node.componentOptions.children = children + node.componentOptions.children = children; } } else { - node.data.on = { ...(node.data.on || {}), ...on } + node.data.on = { ...(node.data.on || {}), ...on }; } if (key !== undefined) { - node.key = key - node.data.key = key + node.key = key; + node.data.key = key; } if (typeof ref === 'string') { - node.data.ref = ref + node.data.ref = ref; } - return node + return node; } - diff --git a/components/_util/vue-types/index.js b/components/_util/vue-types/index.js index 84819ce5e..a53d6afc9 100644 --- a/components/_util/vue-types/index.js +++ b/components/_util/vue-types/index.js @@ -1,231 +1,236 @@ -import isPlainObject from 'lodash/isPlainObject' -import { toType, getType, isFunction, validateType, isInteger, isArray, warn } from './utils' +import isPlainObject from 'lodash/isPlainObject'; +import { toType, getType, isFunction, validateType, isInteger, isArray, warn } from './utils'; const VuePropTypes = { - - get any () { + get any() { return toType('any', { type: null, - }) + }); }, - get func () { + get func() { return toType('function', { type: Function, - }).def(currentDefaults.func) + }).def(currentDefaults.func); }, - get bool () { + get bool() { return toType('boolean', { type: Boolean, - }).def(currentDefaults.bool) + }).def(currentDefaults.bool); }, - get string () { + get string() { return toType('string', { type: String, - }).def(currentDefaults.string) + }).def(currentDefaults.string); }, - get number () { + get number() { return toType('number', { type: Number, - }).def(currentDefaults.number) + }).def(currentDefaults.number); }, - get array () { + get array() { return toType('array', { type: Array, - }).def(currentDefaults.array) + }).def(currentDefaults.array); }, - get object () { + get object() { return toType('object', { type: Object, - }).def(currentDefaults.object) + }).def(currentDefaults.object); }, - get integer () { + get integer() { return toType('integer', { type: Number, - validator (value) { - return isInteger(value) + validator(value) { + return isInteger(value); }, - }).def(currentDefaults.integer) + }).def(currentDefaults.integer); }, - get symbol () { + get symbol() { return toType('symbol', { type: null, - validator (value) { - return typeof value === 'symbol' + validator(value) { + return typeof value === 'symbol'; }, - }) + }); }, - custom (validatorFn, warnMsg = 'custom validation failed') { + custom(validatorFn, warnMsg = 'custom validation failed') { if (typeof validatorFn !== 'function') { - throw new TypeError('[VueTypes error]: You must provide a function as argument') + throw new TypeError('[VueTypes error]: You must provide a function as argument'); } return toType(validatorFn.name || '<>', { - validator (...args) { - const valid = validatorFn(...args) - if (!valid) warn(`${this._vueTypes_name} - ${warnMsg}`) - return valid + validator(...args) { + const valid = validatorFn(...args); + if (!valid) warn(`${this._vueTypes_name} - ${warnMsg}`); + return valid; }, - }) + }); }, - oneOf (arr) { + oneOf(arr) { if (!isArray(arr)) { - throw new TypeError('[VueTypes error]: You must provide an array as argument') + throw new TypeError('[VueTypes error]: You must provide an array as argument'); } - const msg = `oneOf - value should be one of "${arr.join('", "')}"` + const msg = `oneOf - value should be one of "${arr.join('", "')}"`; const allowedTypes = arr.reduce((ret, v) => { if (v !== null && v !== undefined) { - ret.indexOf(v.constructor) === -1 && ret.push(v.constructor) + ret.indexOf(v.constructor) === -1 && ret.push(v.constructor); } - return ret - }, []) + return ret; + }, []); return toType('oneOf', { type: allowedTypes.length > 0 ? allowedTypes : null, - validator (value) { - const valid = arr.indexOf(value) !== -1 - if (!valid) warn(msg) - return valid + validator(value) { + const valid = arr.indexOf(value) !== -1; + if (!valid) warn(msg); + return valid; }, - }) + }); }, - instanceOf (instanceConstructor) { + instanceOf(instanceConstructor) { return toType('instanceOf', { type: instanceConstructor, - }) + }); }, - oneOfType (arr) { + oneOfType(arr) { if (!isArray(arr)) { - throw new TypeError('[VueTypes error]: You must provide an array as argument') + throw new TypeError('[VueTypes error]: You must provide an array as argument'); } - let hasCustomValidators = false + let hasCustomValidators = false; const nativeChecks = arr.reduce((ret, type, i) => { if (isPlainObject(type)) { if (type._vueTypes_name === 'oneOf') { - return ret.concat(type.type || []) + return ret.concat(type.type || []); } if (type.type && !isFunction(type.validator)) { - if (isArray(type.type)) return ret.concat(type.type) - ret.push(type.type) + if (isArray(type.type)) return ret.concat(type.type); + ret.push(type.type); } else if (isFunction(type.validator)) { - hasCustomValidators = true + hasCustomValidators = true; } - return ret + return ret; } - ret.push(type) - return ret - }, []) + ret.push(type); + return ret; + }, []); if (!hasCustomValidators) { // we got just native objects (ie: Array, Object) // delegate to Vue native prop check return toType('oneOfType', { type: nativeChecks, - }).def(undefined) + }).def(undefined); } - const typesStr = arr.map((type) => { - if (type && isArray(type.type)) { - return type.type.map(getType) - } - return getType(type) - }).reduce((ret, type) => ret.concat(isArray(type) ? type : [type]), []).join('", "') - - return this.custom(function oneOfType (value) { - const valid = arr.some((type) => { - if (type._vueTypes_name === 'oneOf') { - return type.type ? validateType(type.type, value, true) : true + const typesStr = arr + .map(type => { + if (type && isArray(type.type)) { + return type.type.map(getType); } - return validateType(type, value, true) + return getType(type); }) - if (!valid) warn(`oneOfType - value type should be one of "${typesStr}"`) - return valid - }).def(undefined) + .reduce((ret, type) => ret.concat(isArray(type) ? type : [type]), []) + .join('", "'); + + return this.custom(function oneOfType(value) { + const valid = arr.some(type => { + if (type._vueTypes_name === 'oneOf') { + return type.type ? validateType(type.type, value, true) : true; + } + return validateType(type, value, true); + }); + if (!valid) warn(`oneOfType - value type should be one of "${typesStr}"`); + return valid; + }).def(undefined); }, - arrayOf (type) { + arrayOf(type) { return toType('arrayOf', { type: Array, - validator (values) { - const valid = values.every((value) => validateType(type, value)) - if (!valid) warn(`arrayOf - value must be an array of "${getType(type)}"`) - return valid + validator(values) { + const valid = values.every(value => validateType(type, value)); + if (!valid) warn(`arrayOf - value must be an array of "${getType(type)}"`); + return valid; }, - }) + }); }, - objectOf (type) { + objectOf(type) { return toType('objectOf', { type: Object, - validator (obj) { - const valid = Object.keys(obj).every((key) => validateType(type, obj[key])) - if (!valid) warn(`objectOf - value must be an object of "${getType(type)}"`) - return valid + validator(obj) { + const valid = Object.keys(obj).every(key => validateType(type, obj[key])); + if (!valid) warn(`objectOf - value must be an object of "${getType(type)}"`); + return valid; }, - }) + }); }, - shape (obj) { - const keys = Object.keys(obj) - const requiredKeys = keys.filter((key) => obj[key] && obj[key].required === true) + shape(obj) { + const keys = Object.keys(obj); + const requiredKeys = keys.filter(key => obj[key] && obj[key].required === true); const type = toType('shape', { type: Object, - validator (value) { + validator(value) { if (!isPlainObject(value)) { - return false + return false; } - const valueKeys = Object.keys(value) + const valueKeys = Object.keys(value); // check for required keys (if any) - if (requiredKeys.length > 0 && requiredKeys.some((req) => valueKeys.indexOf(req) === -1)) { - warn(`shape - at least one of required properties "${requiredKeys.join('", "')}" is not present`) - return false + if (requiredKeys.length > 0 && requiredKeys.some(req => valueKeys.indexOf(req) === -1)) { + warn( + `shape - at least one of required properties "${requiredKeys.join( + '", "', + )}" is not present`, + ); + return false; } - return valueKeys.every((key) => { + return valueKeys.every(key => { if (keys.indexOf(key) === -1) { - if (this._vueTypes_isLoose === true) return true - warn(`shape - object is missing "${key}" property`) - return false + if (this._vueTypes_isLoose === true) return true; + warn(`shape - object is missing "${key}" property`); + return false; } - const type = obj[key] - return validateType(type, value[key]) - }) + const type = obj[key]; + return validateType(type, value[key]); + }); }, - }) + }); Object.defineProperty(type, '_vueTypes_isLoose', { enumerable: false, writable: true, value: false, - }) + }); Object.defineProperty(type, 'loose', { - get () { - this._vueTypes_isLoose = true - return this + get() { + this._vueTypes_isLoose = true; + return this; }, enumerable: false, - }) + }); - return type + return type; }, - -} +}; const typeDefaults = () => ({ func: undefined, @@ -235,24 +240,24 @@ const typeDefaults = () => ({ array: undefined, object: undefined, integer: undefined, -}) +}); -let currentDefaults = typeDefaults() +let currentDefaults = typeDefaults(); Object.defineProperty(VuePropTypes, 'sensibleDefaults', { enumerable: false, - set (value) { + set(value) { if (value === false) { - currentDefaults = {} + currentDefaults = {}; } else if (value === true) { - currentDefaults = typeDefaults() + currentDefaults = typeDefaults(); } else if (isPlainObject(value)) { - currentDefaults = value + currentDefaults = value; } }, - get () { - return currentDefaults + get() { + return currentDefaults; }, -}) +}); -export default VuePropTypes +export default VuePropTypes; diff --git a/components/_util/vue-types/utils.js b/components/_util/vue-types/utils.js index 9554a42da..b56acec0c 100644 --- a/components/_util/vue-types/utils.js +++ b/components/_util/vue-types/utils.js @@ -1,28 +1,28 @@ -import isPlainObject from 'lodash/isPlainObject' +import isPlainObject from 'lodash/isPlainObject'; -const ObjProto = Object.prototype -const toString = ObjProto.toString -export const hasOwn = ObjProto.hasOwnProperty +const ObjProto = Object.prototype; +const toString = ObjProto.toString; +export const hasOwn = ObjProto.hasOwnProperty; -const FN_MATCH_REGEXP = /^\s*function (\w+)/ +const FN_MATCH_REGEXP = /^\s*function (\w+)/; // https://github.com/vuejs/vue/blob/dev/src/core/util/props.js#L159 -export const getType = (fn) => { - const type = (fn !== null && fn !== undefined) ? (fn.type ? fn.type : fn) : null - const match = type && type.toString().match(FN_MATCH_REGEXP) - return match && match[1] -} +export const getType = fn => { + const type = fn !== null && fn !== undefined ? (fn.type ? fn.type : fn) : null; + const match = type && type.toString().match(FN_MATCH_REGEXP); + return match && match[1]; +}; -export const getNativeType = (value) => { - if (value === null || value === undefined) return null - const match = value.constructor.toString().match(FN_MATCH_REGEXP) - return match && match[1] -} +export const getNativeType = value => { + if (value === null || value === undefined) return null; + const match = value.constructor.toString().match(FN_MATCH_REGEXP); + return match && match[1]; +}; /** * No-op function */ -export const noop = () => {} +export const noop = () => {}; /** * Checks for a own property in an object @@ -30,7 +30,7 @@ export const noop = () => {} * @param {object} obj - Object * @param {string} prop - Property to check */ -export const has = (obj, prop) => hasOwn.call(obj, prop) +export const has = (obj, prop) => hasOwn.call(obj, prop); /** * Determines whether the passed value is an integer. Uses `Number.isInteger` if available @@ -39,9 +39,11 @@ export const has = (obj, prop) => hasOwn.call(obj, prop) * @param {*} value - The value to be tested for being an integer. * @returns {boolean} */ -export const isInteger = Number.isInteger || function (value) { - return typeof value === 'number' && isFinite(value) && Math.floor(value) === value -} +export const isInteger = + Number.isInteger || + function(value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; + }; /** * Determines whether the passed value is an Array. @@ -49,9 +51,11 @@ export const isInteger = Number.isInteger || function (value) { * @param {*} value - The value to be tested for being an array. * @returns {boolean} */ -export const isArray = Array.isArray || function (value) { - return toString.call(value) === '[object Array]' -} +export const isArray = + Array.isArray || + function(value) { + return toString.call(value) === '[object Array]'; + }; /** * Checks if a value is a function @@ -59,49 +63,52 @@ export const isArray = Array.isArray || function (value) { * @param {any} value - Value to check * @returns {boolean} */ -export const isFunction = (value) => toString.call(value) === '[object Function]' +export const isFunction = value => toString.call(value) === '[object Function]'; /** * Adds a `def` method to the object returning a new object with passed in argument as `default` property * * @param {object} type - Object to enhance */ -export const withDefault = function (type) { +export const withDefault = function(type) { Object.defineProperty(type, 'def', { - value (def) { + value(def) { if (def === undefined && this.default === undefined) { - this.default = undefined - return this + this.default = undefined; + return this; } if (!isFunction(def) && !validateType(this, def)) { - warn(`${this._vueTypes_name} - invalid default value: "${def}"`, def) - return this + warn(`${this._vueTypes_name} - invalid default value: "${def}"`, def); + return this; } - this.default = (isArray(def) || isPlainObject(def)) ? function () { - return def - } : def + this.default = + isArray(def) || isPlainObject(def) + ? function() { + return def; + } + : def; - return this + return this; }, enumerable: false, writable: false, - }) -} + }); +}; /** * Adds a `isRequired` getter returning a new object with `required: true` key-value * * @param {object} type - Object to enhance */ -export const withRequired = function (type) { +export const withRequired = function(type) { Object.defineProperty(type, 'isRequired', { - get () { - this.required = true - return this + get() { + this.required = true; + return this; }, enumerable: false, - }) -} + }); +}; /** * Adds `isRequired` and `def` modifiers to an object @@ -115,15 +122,15 @@ export const toType = (name, obj) => { enumerable: false, writable: false, value: name, - }) - withRequired(obj) - withDefault(obj) + }); + withRequired(obj); + withDefault(obj); if (isFunction(obj.validator)) { - obj.validator = obj.validator.bind(obj) + obj.validator = obj.validator.bind(obj); } - return obj -} + return obj; +}; /** * Validates a given value against a prop type object @@ -134,55 +141,60 @@ export const toType = (name, obj) => { * @returns {boolean} */ export const validateType = (type, value, silent = false) => { - let typeToCheck = type - let valid = true - let expectedType + let typeToCheck = type; + let valid = true; + let expectedType; if (!isPlainObject(type)) { - typeToCheck = { type } + typeToCheck = { type }; } - const namePrefix = typeToCheck._vueTypes_name ? (typeToCheck._vueTypes_name + ' - ') : '' + const namePrefix = typeToCheck._vueTypes_name ? typeToCheck._vueTypes_name + ' - ' : ''; if (hasOwn.call(typeToCheck, 'type') && typeToCheck.type !== null) { if (isArray(typeToCheck.type)) { - valid = typeToCheck.type.some((type) => validateType(type, value, true)) - expectedType = typeToCheck.type.map((type) => getType(type)).join(' or ') + valid = typeToCheck.type.some(type => validateType(type, value, true)); + expectedType = typeToCheck.type.map(type => getType(type)).join(' or '); } else { - expectedType = getType(typeToCheck) + expectedType = getType(typeToCheck); if (expectedType === 'Array') { - valid = isArray(value) + valid = isArray(value); } else if (expectedType === 'Object') { - valid = isPlainObject(value) - } else if (expectedType === 'String' || expectedType === 'Number' || expectedType === 'Boolean' || expectedType === 'Function') { - valid = getNativeType(value) === expectedType + valid = isPlainObject(value); + } else if ( + expectedType === 'String' || + expectedType === 'Number' || + expectedType === 'Boolean' || + expectedType === 'Function' + ) { + valid = getNativeType(value) === expectedType; } else { - valid = value instanceof typeToCheck.type + valid = value instanceof typeToCheck.type; } } } if (!valid) { - silent === false && warn(`${namePrefix}value "${value}" should be of type "${expectedType}"`) - return false + silent === false && warn(`${namePrefix}value "${value}" should be of type "${expectedType}"`); + return false; } if (hasOwn.call(typeToCheck, 'validator') && isFunction(typeToCheck.validator)) { - valid = typeToCheck.validator(value) - if (!valid && silent === false) warn(`${namePrefix}custom validation failed`) - return valid + valid = typeToCheck.validator(value); + if (!valid && silent === false) warn(`${namePrefix}custom validation failed`); + return valid; } - return valid -} + return valid; +}; -let warn = noop +let warn = noop; if (process.env.NODE_ENV !== 'production') { - const hasConsole = typeof console !== 'undefined' - warn = (msg) => { + const hasConsole = typeof console !== 'undefined'; + warn = msg => { if (hasConsole) { - console.warn(`[VueTypes warn]: ${msg}`) + console.warn(`[VueTypes warn]: ${msg}`); } - } + }; } -export { warn } +export { warn }; diff --git a/components/_util/warning.js b/components/_util/warning.js index f4dd5aa9b..7a12dde23 100644 --- a/components/_util/warning.js +++ b/components/_util/warning.js @@ -1,9 +1,9 @@ -import warning from 'warning' +import warning from 'warning'; -const warned = {} +const warned = {}; export default (valid, message, throwError) => { if (!valid && !warned[message]) { - warning(false, message) - warned[message] = true + warning(false, message); + warned[message] = true; } -} +}; diff --git a/components/_util/wave.jsx b/components/_util/wave.jsx index 396d5d5bc..61cd2ed9e 100644 --- a/components/_util/wave.jsx +++ b/components/_util/wave.jsx @@ -1,161 +1,163 @@ - -import TransitionEvents from './css-animation/Event' -import raf from '../_util/raf' -let styleForPesudo +import TransitionEvents from './css-animation/Event'; +import raf from '../_util/raf'; +let styleForPesudo; // Where el is the DOM element you'd like to test for visibility -function isHidden (element) { +function isHidden(element) { if (process.env.NODE_ENV === 'test') { - return false + return false; } - return !element || element.offsetParent === null + return !element || element.offsetParent === null; } export default { name: 'Wave', props: ['insertExtraNode'], - mounted () { + mounted() { this.$nextTick(() => { - const node = this.$el + const node = this.$el; if (node.nodeType !== 1) { - return + return; } - this.instance = this.bindAnimationEvent(node) - }) + this.instance = this.bindAnimationEvent(node); + }); }, - beforeDestroy () { + beforeDestroy() { if (this.instance) { - this.instance.cancel() + this.instance.cancel(); } if (this.clickWaveTimeoutId) { - clearTimeout(this.clickWaveTimeoutId) + clearTimeout(this.clickWaveTimeoutId); } - this.destroy = true + this.destroy = true; }, methods: { - isNotGrey (color) { - const match = (color || '').match(/rgba?\((\d*), (\d*), (\d*)(, [\.\d]*)?\)/) + isNotGrey(color) { + const match = (color || '').match(/rgba?\((\d*), (\d*), (\d*)(, [\.\d]*)?\)/); if (match && match[1] && match[2] && match[3]) { - return !(match[1] === match[2] && match[2] === match[3]) + return !(match[1] === match[2] && match[2] === match[3]); } - return true + return true; }, - onClick (node, waveColor) { + onClick(node, waveColor) { if (!node || isHidden(node) || node.className.indexOf('-leave') >= 0) { - return + return; } - this.removeExtraStyleNode() - const { insertExtraNode } = this.$props - this.extraNode = document.createElement('div') - const extraNode = this.extraNode - extraNode.className = 'ant-click-animating-node' - const attributeName = this.getAttributeName() - node.removeAttribute(attributeName) - node.setAttribute(attributeName, 'true') + this.removeExtraStyleNode(); + const { insertExtraNode } = this.$props; + this.extraNode = document.createElement('div'); + const extraNode = this.extraNode; + extraNode.className = 'ant-click-animating-node'; + const attributeName = this.getAttributeName(); + node.removeAttribute(attributeName); + node.setAttribute(attributeName, 'true'); // Not white or transparnt or grey - styleForPesudo = styleForPesudo || document.createElement('style') - if (waveColor && - waveColor !== '#ffffff' && - waveColor !== 'rgb(255, 255, 255)' && - this.isNotGrey(waveColor) && - !/rgba\(\d*, \d*, \d*, 0\)/.test(waveColor) && // any transparent rgba color - waveColor !== 'transparent') { - extraNode.style.borderColor = waveColor + styleForPesudo = styleForPesudo || document.createElement('style'); + if ( + waveColor && + waveColor !== '#ffffff' && + waveColor !== 'rgb(255, 255, 255)' && + this.isNotGrey(waveColor) && + !/rgba\(\d*, \d*, \d*, 0\)/.test(waveColor) && // any transparent rgba color + waveColor !== 'transparent' + ) { + extraNode.style.borderColor = waveColor; - styleForPesudo.innerHTML = - `[ant-click-animating-without-extra-node]:after { border-color: ${waveColor}; }` + styleForPesudo.innerHTML = `[ant-click-animating-without-extra-node]:after { border-color: ${waveColor}; }`; if (!document.body.contains(styleForPesudo)) { - document.body.appendChild(styleForPesudo) + document.body.appendChild(styleForPesudo); } } if (insertExtraNode) { - node.appendChild(extraNode) + node.appendChild(extraNode); } - TransitionEvents.addStartEventListener(node, this.onTransitionStart) - TransitionEvents.addEndEventListener(node, this.onTransitionEnd) + TransitionEvents.addStartEventListener(node, this.onTransitionStart); + TransitionEvents.addEndEventListener(node, this.onTransitionEnd); }, - bindAnimationEvent (node) { - if (!node || + bindAnimationEvent(node) { + if ( + !node || !node.getAttribute || node.getAttribute('disabled') || - node.className.indexOf('disabled') >= 0) { - return + node.className.indexOf('disabled') >= 0 + ) { + return; } - const onClick = (e) => { + const onClick = e => { // Fix radio button click twice if (e.target.tagName === 'INPUT' || isHidden(e.target)) { - return + return; } - this.resetEffect(node) + this.resetEffect(node); // Get wave color from target const waveColor = getComputedStyle(node).getPropertyValue('border-top-color') || // Firefox Compatible getComputedStyle(node).getPropertyValue('border-color') || - getComputedStyle(node).getPropertyValue('background-color') - this.clickWaveTimeoutId = window.setTimeout(() => this.onClick(node, waveColor), 0) - raf.cancel(this.animationStartId) - this.animationStart = true + getComputedStyle(node).getPropertyValue('background-color'); + this.clickWaveTimeoutId = window.setTimeout(() => this.onClick(node, waveColor), 0); + raf.cancel(this.animationStartId); + this.animationStart = true; // Render to trigger transition event cost 3 frames. Let's delay 10 frames to reset this. this.animationStartId = raf(() => { - this.animationStart = false - }, 10) - } - node.addEventListener('click', onClick, true) + this.animationStart = false; + }, 10); + }; + node.addEventListener('click', onClick, true); return { cancel: () => { - node.removeEventListener('click', onClick, true) + node.removeEventListener('click', onClick, true); }, - } + }; }, - getAttributeName () { - const { insertExtraNode } = this.$props - return insertExtraNode ? 'ant-click-animating' : 'ant-click-animating-without-extra-node' + getAttributeName() { + const { insertExtraNode } = this.$props; + return insertExtraNode ? 'ant-click-animating' : 'ant-click-animating-without-extra-node'; }, - resetEffect (node) { + resetEffect(node) { if (!node || node === this.extraNode || !(node instanceof Element)) { - return + return; } - const { insertExtraNode } = this.$props - const attributeName = this.getAttributeName() - node.removeAttribute(attributeName) - this.removeExtraStyleNode() + const { insertExtraNode } = this.$props; + const attributeName = this.getAttributeName(); + node.removeAttribute(attributeName); + this.removeExtraStyleNode(); if (insertExtraNode && this.extraNode && node.contains(this.extraNode)) { - node.removeChild(this.extraNode) + node.removeChild(this.extraNode); } - TransitionEvents.removeStartEventListener(node, this.onTransitionStart) - TransitionEvents.removeEndEventListener(node, this.onTransitionEnd) + TransitionEvents.removeStartEventListener(node, this.onTransitionStart); + TransitionEvents.removeEndEventListener(node, this.onTransitionEnd); }, - onTransitionStart (e) { - if (this.destroy) return + onTransitionStart(e) { + if (this.destroy) return; - const node = this.$el + const node = this.$el; if (!e || e.target !== node) { - return + return; } if (!this.animationStart) { - this.resetEffect(node) + this.resetEffect(node); } }, - onTransitionEnd (e) { + onTransitionEnd(e) { if (!e || e.animationName !== 'fadeEffect') { - return + return; } - this.resetEffect(e.target) + this.resetEffect(e.target); }, - removeExtraStyleNode () { + removeExtraStyleNode() { if (styleForPesudo) { - styleForPesudo.innerHTML = '' + styleForPesudo.innerHTML = ''; } }, }, - render () { - return this.$slots.default && this.$slots.default[0] + render() { + return this.$slots.default && this.$slots.default[0]; }, -} +}; diff --git a/components/affix/__tests__/demo.test.js b/components/affix/__tests__/demo.test.js index 41f96aec3..58fcda3f8 100644 --- a/components/affix/__tests__/demo.test.js +++ b/components/affix/__tests__/demo.test.js @@ -1,3 +1,3 @@ -import demoTest from '../../../tests/shared/demoTest' +import demoTest from '../../../tests/shared/demoTest'; -demoTest('affix') +demoTest('affix'); diff --git a/components/affix/__tests__/index.test.js b/components/affix/__tests__/index.test.js index 585e285e7..0450f80a3 100644 --- a/components/affix/__tests__/index.test.js +++ b/components/affix/__tests__/index.test.js @@ -1,116 +1,121 @@ -import Affix from '..' -import Button from '../../button' -import { mount } from '@vue/test-utils' -const events = {} +import Affix from '..'; +import Button from '../../button'; +import { mount } from '@vue/test-utils'; +const events = {}; const AffixMounter = { props: ['offsetBottom', 'offsetTop'], - mounted () { + mounted() { this.$refs.container.addEventListener = jest.fn().mockImplementation((event, cb) => { - events[event] = cb - }) + events[event] = cb; + }); }, methods: { - getTarget () { - return this.$refs.container + getTarget() { + return this.$refs.container; }, }, - render () { + render() { return (
- this.$refs.container} - ref='affix' - {...{ props: this.$props }} - > - + this.$refs.container} ref="affix" {...{ props: this.$props }}> +
- ) + ); }, -} +}; describe('Affix Render', () => { - let wrapper + let wrapper; beforeAll(() => { - document.body.innerHTML = '' - jest.useFakeTimers() - }) + document.body.innerHTML = ''; + jest.useFakeTimers(); + }); afterAll(() => { - jest.useRealTimers() - }) - const scrollTo = (top) => { + jest.useRealTimers(); + }); + const scrollTo = top => { wrapper.vm.$refs.affix.$refs.fixedNode.parentNode.getBoundingClientRect = jest.fn(() => { return { - bottom: 100, height: 28, left: 0, right: 0, top: 50 - top, width: 195, - } - }) - wrapper.vm.$refs.container.scrollTop = top + bottom: 100, + height: 28, + left: 0, + right: 0, + top: 50 - top, + width: 195, + }; + }); + wrapper.vm.$refs.container.scrollTop = top; events.scroll({ type: 'scroll', - }) - jest.runAllTimers() - } + }); + jest.runAllTimers(); + }; it('Anchor render perfectly', () => { - wrapper = mount(AffixMounter, { attachToDocument: true }) - jest.runAllTimers() + wrapper = mount(AffixMounter, { attachToDocument: true }); + jest.runAllTimers(); - scrollTo(0) - expect(wrapper.vm.$refs.affix.affixStyle).toBe(null) + scrollTo(0); + expect(wrapper.vm.$refs.affix.affixStyle).toBe(null); - scrollTo(100) - expect(wrapper.vm.$refs.affix.affixStyle).not.toBe(null) + scrollTo(100); + expect(wrapper.vm.$refs.affix.affixStyle).not.toBe(null); - scrollTo(0) - expect(wrapper.vm.$refs.affix.affixStyle).toBe(null) - }) + scrollTo(0); + expect(wrapper.vm.$refs.affix.affixStyle).toBe(null); + }); it('support offsetBottom', () => { - wrapper = mount(AffixMounter, { attachToDocument: true, propsData: { - offsetBottom: 0, - }}) + wrapper = mount(AffixMounter, { + attachToDocument: true, + propsData: { + offsetBottom: 0, + }, + }); - jest.runAllTimers() + jest.runAllTimers(); - scrollTo(0) - expect(wrapper.vm.$refs.affix.affixStyle).not.toBe(null) + scrollTo(0); + expect(wrapper.vm.$refs.affix.affixStyle).not.toBe(null); - scrollTo(100) - expect(wrapper.vm.$refs.affix.affixStyle).toBe(null) + scrollTo(100); + expect(wrapper.vm.$refs.affix.affixStyle).toBe(null); - scrollTo(0) - expect(wrapper.vm.$refs.affix.affixStyle).not.toBe(null) - }) + scrollTo(0); + expect(wrapper.vm.$refs.affix.affixStyle).not.toBe(null); + }); it('updatePosition when offsetTop changed', () => { - wrapper = mount(AffixMounter, { attachToDocument: true, propsData: { - offsetTop: 0, - }}) + wrapper = mount(AffixMounter, { + attachToDocument: true, + propsData: { + offsetTop: 0, + }, + }); - jest.runAllTimers() + jest.runAllTimers(); - scrollTo(100) - expect(wrapper.vm.$refs.affix.affixStyle.top).toBe('0px') + scrollTo(100); + expect(wrapper.vm.$refs.affix.affixStyle.top).toBe('0px'); wrapper.setProps({ offsetTop: 10, - }) - jest.runAllTimers() - expect(wrapper.vm.$refs.affix.affixStyle.top).toBe('10px') - }) -}) + }); + jest.runAllTimers(); + expect(wrapper.vm.$refs.affix.affixStyle.top).toBe('10px'); + }); +}); diff --git a/components/affix/demo/index.vue b/components/affix/demo/index.vue index d953c643f..eef946b0f 100644 --- a/components/affix/demo/index.vue +++ b/components/affix/demo/index.vue @@ -1,9 +1,9 @@ diff --git a/components/affix/index.jsx b/components/affix/index.jsx index 56df9af4f..dcdc9f970 100644 --- a/components/affix/index.jsx +++ b/components/affix/index.jsx @@ -1,42 +1,37 @@ +import PropTypes from '../_util/vue-types'; +import addEventListener from '../_util/Dom/addEventListener'; +import classNames from 'classnames'; +import shallowequal from 'shallowequal'; +import omit from 'omit.js'; +import getScroll from '../_util/getScroll'; +import BaseMixin from '../_util/BaseMixin'; +import throttleByAnimationFrame from '../_util/throttleByAnimationFrame'; -import PropTypes from '../_util/vue-types' -import addEventListener from '../_util/Dom/addEventListener' -import classNames from 'classnames' -import shallowequal from 'shallowequal' -import omit from 'omit.js' -import getScroll from '../_util/getScroll' -import BaseMixin from '../_util/BaseMixin' -import throttleByAnimationFrame from '../_util/throttleByAnimationFrame' - -function getTargetRect (target) { - return target !== window - ? target.getBoundingClientRect() - : { top: 0, left: 0, bottom: 0 } +function getTargetRect(target) { + return target !== window ? target.getBoundingClientRect() : { top: 0, left: 0, bottom: 0 }; } -function getOffset (element, target) { - const elemRect = element.getBoundingClientRect() - const targetRect = getTargetRect(target) +function getOffset(element, target) { + const elemRect = element.getBoundingClientRect(); + const targetRect = getTargetRect(target); - const scrollTop = getScroll(target, true) - const scrollLeft = getScroll(target, false) + const scrollTop = getScroll(target, true); + const scrollLeft = getScroll(target, false); - const docElem = window.document.body - const clientTop = docElem.clientTop || 0 - const clientLeft = docElem.clientLeft || 0 + const docElem = window.document.body; + const clientTop = docElem.clientTop || 0; + const clientLeft = docElem.clientLeft || 0; return { - top: elemRect.top - targetRect.top + - scrollTop - clientTop, - left: elemRect.left - targetRect.left + - scrollLeft - clientLeft, + top: elemRect.top - targetRect.top + scrollTop - clientTop, + left: elemRect.left - targetRect.left + scrollLeft - clientLeft, width: elemRect.width, height: elemRect.height, - } + }; } -function getDefaultTarget () { - return typeof window !== 'undefined' ? window : null +function getDefaultTarget() { + return typeof window !== 'undefined' ? window : null; } // Affix @@ -53,222 +48,218 @@ const AffixProps = { /** 设置 Affix 需要监听其滚动事件的元素,值为一个返回对应 DOM 元素的函数 */ target: PropTypes.func, prefixCls: PropTypes.string, -} +}; const Affix = { name: 'AAffix', props: AffixProps, mixins: [BaseMixin], - data () { - this.events = [ - 'resize', - 'scroll', - 'touchstart', - 'touchmove', - 'touchend', - 'pageshow', - 'load', - ] - this.eventHandlers = {} + data() { + this.events = ['resize', 'scroll', 'touchstart', 'touchmove', 'touchend', 'pageshow', 'load']; + this.eventHandlers = {}; return { affixStyle: undefined, placeholderStyle: undefined, - } + }; }, - beforeMount () { - this.updatePosition = throttleByAnimationFrame(this.updatePosition) + beforeMount() { + this.updatePosition = throttleByAnimationFrame(this.updatePosition); }, - mounted () { - const target = this.target || getDefaultTarget + mounted() { + const target = this.target || getDefaultTarget; // Wait for parent component ref has its value this.timeout = setTimeout(() => { - this.setTargetEventListeners(target) + this.setTargetEventListeners(target); // Mock Event object. - this.updatePosition({}) - }) + this.updatePosition({}); + }); }, watch: { - target (val) { - this.clearEventListeners() - this.setTargetEventListeners(val) + target(val) { + this.clearEventListeners(); + this.setTargetEventListeners(val); // Mock Event object. - this.updatePosition({}) + this.updatePosition({}); }, - offsetTop (val) { - this.updatePosition({}) + offsetTop(val) { + this.updatePosition({}); }, - offsetBottom (val) { - this.updatePosition({}) + offsetBottom(val) { + this.updatePosition({}); }, }, - beforeDestroy () { - this.clearEventListeners() - clearTimeout(this.timeout) - this.updatePosition.cancel() + beforeDestroy() { + this.clearEventListeners(); + clearTimeout(this.timeout); + this.updatePosition.cancel(); }, methods: { - setAffixStyle (e, affixStyle) { - const { target = getDefaultTarget } = this - const originalAffixStyle = this.affixStyle - const isWindow = target() === window + setAffixStyle(e, affixStyle) { + const { target = getDefaultTarget } = this; + const originalAffixStyle = this.affixStyle; + const isWindow = target() === window; if (e.type === 'scroll' && originalAffixStyle && affixStyle && isWindow) { - return + return; } if (shallowequal(affixStyle, originalAffixStyle)) { - return + return; } this.setState({ affixStyle: affixStyle }, () => { - const affixed = !!this.affixStyle - if ((affixStyle && !originalAffixStyle) || - (!affixStyle && originalAffixStyle)) { - this.$emit('change', affixed) + const affixed = !!this.affixStyle; + if ((affixStyle && !originalAffixStyle) || (!affixStyle && originalAffixStyle)) { + this.$emit('change', affixed); } - }) + }); }, - setPlaceholderStyle (placeholderStyle) { - const originalPlaceholderStyle = this.placeholderStyle + setPlaceholderStyle(placeholderStyle) { + const originalPlaceholderStyle = this.placeholderStyle; if (shallowequal(placeholderStyle, originalPlaceholderStyle)) { - return + return; } - this.setState({ placeholderStyle: placeholderStyle }) + this.setState({ placeholderStyle: placeholderStyle }); }, - syncPlaceholderStyle (e) { - const { affixStyle } = this + syncPlaceholderStyle(e) { + const { affixStyle } = this; if (!affixStyle) { - return + return; } - this.$refs.placeholderNode.style.cssText = '' + this.$refs.placeholderNode.style.cssText = ''; this.setAffixStyle(e, { ...affixStyle, width: this.$refs.placeholderNode.offsetWidth + 'px', - }) + }); this.setPlaceholderStyle({ width: this.$refs.placeholderNode.offsetWidth + 'px', - }) + }); }, - updatePosition (e) { - const { offsetBottom, offset, target = getDefaultTarget } = this - let { offsetTop } = this - const targetNode = target() + updatePosition(e) { + const { offsetBottom, offset, target = getDefaultTarget } = this; + let { offsetTop } = this; + const targetNode = target(); // Backwards support // Fix: if offsetTop === 0, it will get undefined, // if offsetBottom is type of number, offsetMode will be { top: false, ... } - offsetTop = typeof offsetTop === 'undefined' ? offset : offsetTop - const scrollTop = getScroll(targetNode, true) - const affixNode = this.$el - const elemOffset = getOffset(affixNode, targetNode) + offsetTop = typeof offsetTop === 'undefined' ? offset : offsetTop; + const scrollTop = getScroll(targetNode, true); + const affixNode = this.$el; + const elemOffset = getOffset(affixNode, targetNode); const elemSize = { width: this.$refs.fixedNode.offsetWidth, height: this.$refs.fixedNode.offsetHeight, - } + }; const offsetMode = { top: false, bottom: false, - } + }; // Default to `offsetTop=0`. if (typeof offsetTop !== 'number' && typeof offsetBottom !== 'number') { - offsetMode.top = true - offsetTop = 0 + offsetMode.top = true; + offsetTop = 0; } else { - offsetMode.top = typeof offsetTop === 'number' - offsetMode.bottom = typeof offsetBottom === 'number' + offsetMode.top = typeof offsetTop === 'number'; + offsetMode.bottom = typeof offsetBottom === 'number'; } - const targetRect = getTargetRect(targetNode) - const targetInnerHeight = - targetNode.innerHeight || targetNode.clientHeight + const targetRect = getTargetRect(targetNode); + const targetInnerHeight = targetNode.innerHeight || targetNode.clientHeight; if (scrollTop > elemOffset.top - offsetTop && offsetMode.top) { - // Fixed Top - const width = `${elemOffset.width}px` - const top = `${targetRect.top + offsetTop}px` + // Fixed Top + const width = `${elemOffset.width}px`; + const top = `${targetRect.top + offsetTop}px`; this.setAffixStyle(e, { position: 'fixed', top, left: `${targetRect.left + elemOffset.left}px`, width, - }) + }); this.setPlaceholderStyle({ width, height: `${elemSize.height}px`, - }) + }); } else if ( scrollTop < elemOffset.top + elemSize.height + offsetBottom - targetInnerHeight && offsetMode.bottom ) { - // Fixed Bottom - const targetBottomOffet = targetNode === window ? 0 : (window.innerHeight - targetRect.bottom) - const width = `${elemOffset.width}px` + // Fixed Bottom + const targetBottomOffet = + targetNode === window ? 0 : window.innerHeight - targetRect.bottom; + const width = `${elemOffset.width}px`; this.setAffixStyle(e, { position: 'fixed', bottom: targetBottomOffet + offsetBottom + 'px', left: targetRect.left + elemOffset.left + 'px', width, - }) + }); this.setPlaceholderStyle({ width, height: elemOffset.height + 'px', - }) + }); } else { - const { affixStyle } = this - if (e.type === 'resize' && affixStyle && affixStyle.position === 'fixed' && affixNode.offsetWidth) { - this.setAffixStyle(e, { ...affixStyle, width: affixNode.offsetWidth + 'px' }) + const { affixStyle } = this; + if ( + e.type === 'resize' && + affixStyle && + affixStyle.position === 'fixed' && + affixNode.offsetWidth + ) { + this.setAffixStyle(e, { ...affixStyle, width: affixNode.offsetWidth + 'px' }); } else { - this.setAffixStyle(e, null) + this.setAffixStyle(e, null); } - this.setPlaceholderStyle(null) + this.setPlaceholderStyle(null); } if (e.type === 'resize') { - this.syncPlaceholderStyle(e) + this.syncPlaceholderStyle(e); } }, - setTargetEventListeners (getTarget) { - const target = getTarget() + setTargetEventListeners(getTarget) { + const target = getTarget(); if (!target) { - return + return; } - this.clearEventListeners() + this.clearEventListeners(); this.events.forEach(eventName => { - this.eventHandlers[eventName] = addEventListener(target, eventName, this.updatePosition) - }) + this.eventHandlers[eventName] = addEventListener(target, eventName, this.updatePosition); + }); }, - clearEventListeners () { + clearEventListeners() { this.events.forEach(eventName => { - const handler = this.eventHandlers[eventName] + const handler = this.eventHandlers[eventName]; if (handler && handler.remove) { - handler.remove() + handler.remove(); } - }) + }); }, }, - render () { - const { prefixCls, affixStyle, placeholderStyle, $slots, $props } = this + render() { + const { prefixCls, affixStyle, placeholderStyle, $slots, $props } = this; const className = classNames({ [prefixCls || 'ant-affix']: affixStyle, - }) + }); const props = { attrs: omit($props, ['prefixCls', 'offsetTop', 'offsetBottom', 'target']), - } + }; return ( -
-
+
+
{$slots.default}
- ) + ); }, -} +}; /* istanbul ignore next */ -Affix.install = function (Vue) { - Vue.component(Affix.name, Affix) -} +Affix.install = function(Vue) { + Vue.component(Affix.name, Affix); +}; -export default Affix +export default Affix; diff --git a/components/alert/__tests__/demo.test.js b/components/alert/__tests__/demo.test.js index 82b36db3d..081086401 100644 --- a/components/alert/__tests__/demo.test.js +++ b/components/alert/__tests__/demo.test.js @@ -1,3 +1,3 @@ -import demoTest from '../../../tests/shared/demoTest' +import demoTest from '../../../tests/shared/demoTest'; -demoTest('alert') +demoTest('alert'); diff --git a/components/alert/__tests__/index.test.js b/components/alert/__tests__/index.test.js index d78490454..bb04ba8ce 100644 --- a/components/alert/__tests__/index.test.js +++ b/components/alert/__tests__/index.test.js @@ -1,69 +1,71 @@ -import { mount } from '@vue/test-utils' -import Alert from '..' +import { mount } from '@vue/test-utils'; +import Alert from '..'; describe('Alert', () => { beforeAll(() => { - jest.useFakeTimers() - }) + jest.useFakeTimers(); + }); afterAll(() => { - jest.useRealTimers() - }) + jest.useRealTimers(); + }); it('could be closed', () => { - const onClose = jest.fn() - const afterClose = jest.fn() + const onClose = jest.fn(); + const afterClose = jest.fn(); const wrapper = mount({ - render () { - return + render() { + return ( + + ); }, - }) - wrapper.find('.ant-alert-close-icon').trigger('click') - expect(onClose).toBeCalled() - jest.runAllTimers() - wrapper.vm.$refs.alert.animationEnd() - expect(afterClose).toBeCalled() - }) + }); + wrapper.find('.ant-alert-close-icon').trigger('click'); + expect(onClose).toBeCalled(); + jest.runAllTimers(); + wrapper.vm.$refs.alert.animationEnd(); + expect(afterClose).toBeCalled(); + }); describe('data and aria props', () => { it('sets data attributes on input', () => { const wrapper = mount({ - render () { - return + render() { + return ; }, - }) - const input = wrapper.find('.ant-alert').element - expect(input.getAttribute('data-test')).toBe('test-id') - expect(input.getAttribute('data-id')).toBe('12345') - }) + }); + const input = wrapper.find('.ant-alert').element; + expect(input.getAttribute('data-test')).toBe('test-id'); + expect(input.getAttribute('data-id')).toBe('12345'); + }); it('sets aria attributes on input', () => { const wrapper = mount({ - render () { - return + render() { + return ; }, - }) + }); - const input = wrapper.find('.ant-alert').element - expect(input.getAttribute('aria-describedby')).toBe('some-label') - }) + const input = wrapper.find('.ant-alert').element; + expect(input.getAttribute('aria-describedby')).toBe('some-label'); + }); it('sets role attribute on input', () => { const wrapper = mount({ - render () { - return + render() { + return ; }, - }) + }); - const input = wrapper.find('.ant-alert').element - expect(input.getAttribute('role')).toBe('status') - }) - }) -}) + const input = wrapper.find('.ant-alert').element; + expect(input.getAttribute('role')).toBe('status'); + }); + }); +}); diff --git a/components/alert/demo/index.vue b/components/alert/demo/index.vue index 9d693b75f..a65a0a85a 100644 --- a/components/alert/demo/index.vue +++ b/components/alert/demo/index.vue @@ -1,15 +1,15 @@ +

滚动

@@ -92,11 +92,7 @@ export default { height: '500px', }} > - + 开始上传2
@@ -104,6 +100,6 @@ export default {
- ) + ); }, -} +}; diff --git a/components/vc-upload/index.js b/components/vc-upload/index.js index 7b0871dec..ed11064e8 100644 --- a/components/vc-upload/index.js +++ b/components/vc-upload/index.js @@ -1,4 +1,4 @@ // rc-upload 2.6.0 -import upload from './src' +import upload from './src'; -export default upload +export default upload; diff --git a/components/vc-upload/src/AjaxUploader.jsx b/components/vc-upload/src/AjaxUploader.jsx index a9bdb7714..e9ec6adc7 100644 --- a/components/vc-upload/src/AjaxUploader.jsx +++ b/components/vc-upload/src/AjaxUploader.jsx @@ -1,10 +1,10 @@ -import PropTypes from '../../_util/vue-types' -import BaseMixin from '../../_util/BaseMixin' -import classNames from 'classnames' -import defaultRequest from './request' -import getUid from './uid' -import attrAccept from './attr-accept' -import traverseFileTree from './traverseFileTree' +import PropTypes from '../../_util/vue-types'; +import BaseMixin from '../../_util/BaseMixin'; +import classNames from 'classnames'; +import defaultRequest from './request'; +import getUid from './uid'; +import attrAccept from './attr-accept'; +import traverseFileTree from './traverseFileTree'; const upLoadPropTypes = { componentTag: PropTypes.string, @@ -18,121 +18,115 @@ const upLoadPropTypes = { accept: PropTypes.string, // children: PropTypes.any, // onStart: PropTypes.func, - data: PropTypes.oneOfType([ - PropTypes.object, - PropTypes.func, - ]), - action: PropTypes.oneOfType([ - PropTypes.string, - PropTypes.func, - ]), + data: PropTypes.oneOfType([PropTypes.object, PropTypes.func]), + action: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), headers: PropTypes.object, beforeUpload: PropTypes.func, customRequest: PropTypes.func, // onProgress: PropTypes.func, withCredentials: PropTypes.bool, openFileDialogOnClick: PropTypes.bool, -} +}; const AjaxUploader = { inheritAttrs: false, name: 'ajaxUploader', mixins: [BaseMixin], props: upLoadPropTypes, - data () { - this.reqs = {} + data() { + this.reqs = {}; return { uid: getUid(), - } + }; }, - mounted () { - this._isMounted = true + mounted() { + this._isMounted = true; }, - beforeDestroy () { - this._isMounted = false - this.abort() + beforeDestroy() { + this._isMounted = false; + this.abort(); }, methods: { - onChange (e) { - const files = e.target.files - this.uploadFiles(files) - this.reset() + onChange(e) { + const files = e.target.files; + this.uploadFiles(files); + this.reset(); }, - onClick () { - const el = this.$refs.fileInputRef + onClick() { + const el = this.$refs.fileInputRef; if (!el) { - return + return; } - el.click() + el.click(); }, - onKeyDown (e) { + onKeyDown(e) { if (e.key === 'Enter') { - this.onClick() + this.onClick(); } }, - onFileDrop (e) { - e.preventDefault() + onFileDrop(e) { + e.preventDefault(); if (e.type === 'dragover') { - return + return; } if (this.directory) { - traverseFileTree( - e.dataTransfer.items, - this.uploadFiles, - _file => attrAccept(_file, this.accept) - ) + traverseFileTree(e.dataTransfer.items, this.uploadFiles, _file => + attrAccept(_file, this.accept), + ); } else { - const files = Array.prototype.slice.call(e.dataTransfer.files).filter( - file => attrAccept(file, this.accept) - ) - this.uploadFiles(files) + const files = Array.prototype.slice + .call(e.dataTransfer.files) + .filter(file => attrAccept(file, this.accept)); + this.uploadFiles(files); } }, - uploadFiles (files) { - const postFiles = Array.prototype.slice.call(files) - postFiles.forEach((file) => { - file.uid = getUid() - this.upload(file, postFiles) - }) + uploadFiles(files) { + const postFiles = Array.prototype.slice.call(files); + postFiles.forEach(file => { + file.uid = getUid(); + this.upload(file, postFiles); + }); }, - upload (file, fileList) { + upload(file, fileList) { if (!this.beforeUpload) { // always async in case use react state to keep fileList - return setTimeout(() => this.post(file), 0) + return setTimeout(() => this.post(file), 0); } - const before = this.beforeUpload(file, fileList) + const before = this.beforeUpload(file, fileList); if (before && before.then) { - before.then((processedFile) => { - const processedFileType = Object.prototype.toString.call(processedFile) - if (processedFileType === '[object File]' || processedFileType === '[object Blob]') { - return this.post(processedFile) - } - return this.post(file) - }).catch(e => { - console && console.log(e); // eslint-disable-line - }) + before + .then(processedFile => { + const processedFileType = Object.prototype.toString.call(processedFile); + if (processedFileType === '[object File]' || processedFileType === '[object Blob]') { + return this.post(processedFile); + } + return this.post(file); + }) + .catch(e => { + console && console.log(e); // eslint-disable-line + }); } else if (before !== false) { - setTimeout(() => this.post(file), 0) + setTimeout(() => this.post(file), 0); } }, - post (file) { + post(file) { if (!this._isMounted) { - return + return; } - let { data } = this.$props + let { data } = this.$props; if (typeof data === 'function') { - data = data(file) + data = data(file); } new Promise(resolve => { - const { action } = this + const { action } = this; if (typeof action === 'function') { - return resolve(action(file)) + return resolve(action(file)); } - resolve(action) + resolve(action); }).then(action => { - const { uid } = file - const request = this.customRequest || defaultRequest + const { uid } = file; + const request = this.customRequest || defaultRequest; this.reqs[uid] = request({ action, filename: this.name, @@ -141,64 +135,71 @@ const AjaxUploader = { headers: this.headers, withCredentials: this.withCredentials, onProgress: e => { - this.$emit('progress', e, file) + this.$emit('progress', e, file); }, onSuccess: (ret, xhr) => { - delete this.reqs[uid] - this.$emit('success', ret, file, xhr) + delete this.reqs[uid]; + this.$emit('success', ret, file, xhr); }, onError: (err, ret) => { - delete this.reqs[uid] - this.$emit('error', err, ret, file) + delete this.reqs[uid]; + this.$emit('error', err, ret, file); }, - }) - this.$emit('start', file) - }) + }); + this.$emit('start', file); + }); }, - reset () { + reset() { this.setState({ uid: getUid(), - }) + }); }, - abort (file) { - const { reqs } = this + abort(file) { + const { reqs } = this; if (file) { - let uid = file + let uid = file; if (file && file.uid) { - uid = file.uid + uid = file.uid; } if (reqs[uid]) { - reqs[uid].abort() - delete reqs[uid] + reqs[uid].abort(); + delete reqs[uid]; } } else { - Object.keys(reqs).forEach((uid) => { + Object.keys(reqs).forEach(uid => { if (reqs[uid]) { - reqs[uid].abort() + reqs[uid].abort(); } - delete reqs[uid] - }) + delete reqs[uid]; + }); } }, }, - render () { - const { $props, $attrs } = this + render() { + const { $props, $attrs } = this; const { - componentTag: Tag, prefixCls, disabled, - multiple, accept, directory, openFileDialogOnClick, - } = $props + componentTag: Tag, + prefixCls, + disabled, + multiple, + accept, + directory, + openFileDialogOnClick, + } = $props; const cls = classNames({ [prefixCls]: true, [`${prefixCls}-disabled`]: disabled, - }) - const events = disabled ? {} : { - click: openFileDialogOnClick ? this.onClick : () => {}, - keydown: this.onKeyDown, - drop: this.onFileDrop, - dragover: this.onFileDrop, - } + }); + const events = disabled + ? {} + : { + click: openFileDialogOnClick ? this.onClick : () => {}, + keydown: this.onKeyDown, + drop: this.onFileDrop, + dragover: this.onFileDrop, + }; const tagProps = { on: { ...this.$listeners, @@ -209,15 +210,13 @@ const AjaxUploader = { tabIndex: disabled ? null : '0', }, class: cls, - } + }; return ( - + {this.$slots.default} - ) + ); }, -} +}; -export default AjaxUploader +export default AjaxUploader; diff --git a/components/vc-upload/src/IframeUploader.jsx b/components/vc-upload/src/IframeUploader.jsx index 911c9f688..a6e8ed407 100644 --- a/components/vc-upload/src/IframeUploader.jsx +++ b/components/vc-upload/src/IframeUploader.jsx @@ -1,8 +1,8 @@ -import PropTypes from '../../_util/vue-types' -import BaseMixin from '../../_util/BaseMixin' -import classNames from 'classnames' -import getUid from './uid' -import warning from '../../_util/warning' +import PropTypes from '../../_util/vue-types'; +import BaseMixin from '../../_util/BaseMixin'; +import classNames from 'classnames'; +import getUid from './uid'; +import warning from '../../_util/warning'; const IFRAME_STYLE = { position: 'absolute', @@ -11,7 +11,7 @@ const IFRAME_STYLE = { filter: 'alpha(opacity=0)', left: 0, zIndex: 9999, -} +}; // diferent from AjaxUpload, can only upload on at one time, serial seriously const IframeUploader = { @@ -26,95 +26,95 @@ const IframeUploader = { // onStart: PropTypes.func, multiple: PropTypes.bool, // children: PropTypes.any, - data: PropTypes.oneOfType([ - PropTypes.object, - PropTypes.func, - ]), - action: PropTypes.oneOfType([ - PropTypes.string, - PropTypes.func, - ]), + data: PropTypes.oneOfType([PropTypes.object, PropTypes.func]), + action: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), name: PropTypes.string, }, - data () { - this.file = {} + data() { + this.file = {}; return { uploading: false, - } + }; }, methods: { - onLoad () { + onLoad() { if (!this.uploading) { - return + return; } - const { file } = this - let response + const { file } = this; + let response; try { - const doc = this.getIframeDocument() - const script = doc.getElementsByTagName('script')[0] + const doc = this.getIframeDocument(); + const script = doc.getElementsByTagName('script')[0]; if (script && script.parentNode === doc.body) { - doc.body.removeChild(script) + doc.body.removeChild(script); } - response = doc.body.innerHTML - this.$emit('success', response, file) + response = doc.body.innerHTML; + this.$emit('success', response, file); } catch (err) { - warning(false, 'cross domain error for Upload. Maybe server should return document.domain script. see Note from https://github.com/react-component/upload') - response = 'cross-domain' - this.$emit('error', err, null, file) + warning( + false, + 'cross domain error for Upload. Maybe server should return document.domain script. see Note from https://github.com/react-component/upload', + ); + response = 'cross-domain'; + this.$emit('error', err, null, file); } - this.endUpload() + this.endUpload(); }, - onChange () { - const target = this.getFormInputNode() + onChange() { + const target = this.getFormInputNode(); // ie8/9 don't support FileList Object // http://stackoverflow.com/questions/12830058/ie8-input-type-file-get-files - const file = this.file = { + const file = (this.file = { uid: getUid(), name: target.value, - } - this.startUpload() - const { $props: props } = this + }); + this.startUpload(); + const { $props: props } = this; if (!props.beforeUpload) { - return this.post(file) + return this.post(file); } - const before = props.beforeUpload(file) + const before = props.beforeUpload(file); if (before && before.then) { - before.then(() => { - this.post(file) - }, () => { - this.endUpload() - }) + before.then( + () => { + this.post(file); + }, + () => { + this.endUpload(); + }, + ); } else if (before !== false) { - this.post(file) + this.post(file); } else { - this.endUpload() + this.endUpload(); } }, - getIframeNode () { - return this.$refs.iframeRef + getIframeNode() { + return this.$refs.iframeRef; }, - getIframeDocument () { - return this.getIframeNode().contentDocument + getIframeDocument() { + return this.getIframeNode().contentDocument; }, - getFormNode () { - return this.getIframeDocument().getElementById('form') + getFormNode() { + return this.getIframeDocument().getElementById('form'); }, - getFormInputNode () { - return this.getIframeDocument().getElementById('input') + getFormInputNode() { + return this.getIframeDocument().getElementById('input'); }, - getFormDataNode () { - return this.getIframeDocument().getElementById('data') + getFormDataNode() { + return this.getIframeDocument().getElementById('data'); }, - getFileForMultiple (file) { - return this.multiple ? [file] : file + getFileForMultiple(file) { + return this.multiple ? [file] : file; }, - getIframeHTML (domain) { - let domainScript = '' - let domainInput = '' + getIframeHTML(domain) { + let domainScript = ''; + let domainInput = ''; if (domain) { - const script = 'script' - domainScript = `<${script}>document.domain="${domain}";` - domainInput = `` + const script = 'script'; + domainScript = `<${script}>document.domain="${domain}";`; + domainInput = ``; } return ` @@ -139,9 +139,9 @@ const IframeUploader = { - ` + `; }, - initIframeSrc () { + initIframeSrc() { if (this.domain) { this.getIframeNode().src = `javascript:void((function(){ var d = document; @@ -149,137 +149,127 @@ const IframeUploader = { d.domain='${this.domain}'; d.write(''); d.close(); - })())` + })())`; } }, - initIframe () { - const iframeNode = this.getIframeNode() - let win = iframeNode.contentWindow - let doc - this.domain = this.domain || '' - this.initIframeSrc() + initIframe() { + const iframeNode = this.getIframeNode(); + let win = iframeNode.contentWindow; + let doc; + this.domain = this.domain || ''; + this.initIframeSrc(); try { - doc = win.document + doc = win.document; } catch (e) { - this.domain = document.domain - this.initIframeSrc() - win = iframeNode.contentWindow - doc = win.document + this.domain = document.domain; + this.initIframeSrc(); + win = iframeNode.contentWindow; + doc = win.document; } - doc.open('text/html', 'replace') - doc.write(this.getIframeHTML(this.domain)) - doc.close() - this.getFormInputNode().onchange = this.onChange + doc.open('text/html', 'replace'); + doc.write(this.getIframeHTML(this.domain)); + doc.close(); + this.getFormInputNode().onchange = this.onChange; }, - endUpload () { + endUpload() { if (this.uploading) { - this.file = {} + this.file = {}; // hack avoid batch - this.uploading = false + this.uploading = false; this.setState({ uploading: false, - }) - this.initIframe() + }); + this.initIframe(); } }, - startUpload () { + startUpload() { if (!this.uploading) { - this.uploading = true + this.uploading = true; this.setState({ uploading: true, - }) + }); } }, - updateIframeWH () { - const rootNode = this.$el - const iframeNode = this.getIframeNode() - iframeNode.style.height = `${rootNode.offsetHeight}px` - iframeNode.style.width = `${rootNode.offsetWidth}px` + updateIframeWH() { + const rootNode = this.$el; + const iframeNode = this.getIframeNode(); + iframeNode.style.height = `${rootNode.offsetHeight}px`; + iframeNode.style.width = `${rootNode.offsetWidth}px`; }, - abort (file) { + abort(file) { if (file) { - let uid = file + let uid = file; if (file && file.uid) { - uid = file.uid + uid = file.uid; } if (uid === this.file.uid) { - this.endUpload() + this.endUpload(); } } else { - this.endUpload() + this.endUpload(); } }, - post (file) { - const formNode = this.getFormNode() - const dataSpan = this.getFormDataNode() - let { data } = this.$props + post(file) { + const formNode = this.getFormNode(); + const dataSpan = this.getFormDataNode(); + let { data } = this.$props; if (typeof data === 'function') { - data = data(file) + data = data(file); } - const inputs = document.createDocumentFragment() + const inputs = document.createDocumentFragment(); for (const key in data) { if (data.hasOwnProperty(key)) { - const input = document.createElement('input') - input.setAttribute('name', key) - input.value = data[key] - inputs.appendChild(input) + const input = document.createElement('input'); + input.setAttribute('name', key); + input.value = data[key]; + inputs.appendChild(input); } } - dataSpan.appendChild(inputs) + dataSpan.appendChild(inputs); new Promise(resolve => { - const { action } = this + const { action } = this; if (typeof action === 'function') { - return resolve(action(file)) + return resolve(action(file)); } - resolve(action) + resolve(action); }).then(action => { - formNode.setAttribute('action', action) - formNode.submit() - dataSpan.innerHTML = '' - this.$emit('start', file) - }) + formNode.setAttribute('action', action); + formNode.submit(); + dataSpan.innerHTML = ''; + this.$emit('start', file); + }); }, }, - mounted () { + mounted() { this.$nextTick(() => { - this.updateIframeWH() - this.initIframe() - }) + this.updateIframeWH(); + this.initIframe(); + }); }, - updated () { + updated() { this.$nextTick(() => { - this.updateIframeWH() - }) + this.updateIframeWH(); + }); }, - render () { - const { - componentTag: Tag, disabled, - prefixCls, - } = this.$props + render() { + const { componentTag: Tag, disabled, prefixCls } = this.$props; const iframeStyle = { ...IFRAME_STYLE, display: this.uploading || disabled ? 'none' : '', - } + }; const cls = classNames({ [prefixCls]: true, [`${prefixCls}-disabled`]: disabled, - }) + }); return ( - -