浏览代码

fix: fix some bugs

yhhu 6 年之前
父节点
当前提交
c60a4c9713

+ 3 - 0
.gitignore

@@ -60,3 +60,6 @@ output
 *.ipa
 *.dSYM.zip
 *.dSYM
+
+## release
+dist/

+ 2 - 2
dist/index.html

@@ -4,13 +4,13 @@
 	<meta charset="UTF-8">
 	<title>Datepicker</title>
 	
-		<link href="main.7bcd97632367f921e277.css" rel="stylesheet">
+		<link href="main.4622b6314fea50e76437.css" rel="stylesheet">
 	
 </head>
 <body>
 	<div id="container" class="container"></div>
 	
-		<script src="main-bundle-7bcd9763.js"></script>
+		<script src="main-bundle-4622b631.js"></script>
 	
 </body>
 </html>

文件差异内容过多而无法显示
+ 0 - 41
dist/main-bundle-7bcd9763.js


文件差异内容过多而无法显示
+ 0 - 7
dist/main.7bcd97632367f921e277.css


+ 12 - 0
docs/index.html

@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="UTF-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0">
+  <meta http-equiv="X-UA-Compatible" content="ie=edge">
+  <title>DatePicker examples</title>
+</head>
+<body>
+  index
+</body>
+</html>

+ 12 - 0
src/app.js

@@ -0,0 +1,12 @@
+
+import React from 'react'
+import ReactDOM from 'react-dom'
+import DatePicker from './index'
+
+const App = () => (
+  <DatePicker
+    placeholder="please choose date"
+    onSelectDate={day => console.log(day)}
+  />
+)
+ReactDOM.render(<App />, document.getElementById('container'))

+ 15 - 11
src/components/calendar/Header.js

@@ -12,18 +12,22 @@ const Header = () => (
         onPrevYear,
         onNextMonth,
         onNextYear,
-      }) => (
-        <div className={Styles.wrapper}>
-          <i className={Styles.prevYear} role="presentation" title="上一年" onClick={e => onPrevYear(e)} />
-          <i className={Styles.prevMonth} role="presentation" title="上一月" onClick={e => onPrevMonth(e)} />
-          <div className={Styles.text}>
-            <span className={Styles.link}>{`${year}年`}</span>
-            <span className={Styles.link}>{`${month}月`}</span>
+      }) => {
+        console.log('Header year', year)
+        console.log('Header month', month)
+        return (
+          <div className={Styles.wrapper}>
+            <i className={Styles.prevYear} role="presentation" title="上一年" onClick={e => onPrevYear(e)} />
+            <i className={Styles.prevMonth} role="presentation" title="上一月" onClick={e => onPrevMonth(e)} />
+            <div className={Styles.text}>
+              <span className={Styles.link}>{`${year}年`}</span>
+              <span className={Styles.link}>{`${month}月`}</span>
+            </div>
+            <i className={Styles.nextMonth} role="presentation" title="下一月" onClick={e => onNextMonth(e)} />
+            <i className={Styles.nextYear} role="presentation" title="下一年" onClick={e => onNextYear(e)} />
           </div>
-          <i className={Styles.nextMonth} role="presentation" title="下一月" onClick={e => onNextMonth(e)} />
-          <i className={Styles.nextYear} role="presentation" title="下一年" onClick={e => onNextYear(e)} />
-        </div>
-      )
+        )
+      }
     }
 
   </DateContext.Consumer>

+ 42 - 37
src/components/index/DatePicker.js

@@ -9,7 +9,7 @@ import {
 } from '../../utils'
 import Modal from '../modal/Modal'
 import {
-  CHINESE_MODEL, WESTERN_MODEL, _, noop,
+  CHINESE_MODEL, WESTERN_MODEL, _, INPUT_DEFAULT_PLACEHOLDER,
 } from '../../const'
 import { DateContext, initialData } from '../../context'
 import {
@@ -20,6 +20,7 @@ import {
   getPrevYearAndMonth,
   getNextYearAndMonth,
   isInCurrentMonth,
+  resetCalendarFromSpecialDay,
 } from '../../helper'
 import '../../utils/closest-polyfill'
 
@@ -51,6 +52,7 @@ class DatePicker extends Component {
     })
   }
 
+  /* eslint-disable no-underscore-dangle */
   onModalOpen = () => {
     this.setState({ showModal: true })
   }
@@ -75,7 +77,7 @@ class DatePicker extends Component {
   }
 
   onChangeModel = model => {
-    const { value } = this.state
+    const { value, year, month } = this.state
     let nextModel = model
     if (model === CHINESE_MODEL) {
       nextModel = WESTERN_MODEL
@@ -84,7 +86,7 @@ class DatePicker extends Component {
     }
 
     const weekTags = getWeekSort(nextModel)
-    const changeModelDays = getDaysOfMonth(_, _, nextModel)
+    const changeModelDays = getDaysOfMonth(year, month, nextModel)
     const afterSetDays = setSelectedDays(changeModelDays, value)
     this.setState({
       model: nextModel,
@@ -93,51 +95,50 @@ class DatePicker extends Component {
     })
   }
 
-  _onChangeYearOrMonth = (
-    changeYear,
-    changeMonth,
-    callback = noop,
-    format,
-  ) => {
+  _selectDayCallback = day => {
+    const { onSelectDate } = this.props
+    this.onModalClose()
+    onSelectDate(day)
+  }
+
+  onSelectDay = day => {
     const {
-      model, value, year, month,
+      days, value, year, month,
     } = this.state
-    const dayFormat = format || value
-    const days = getDaysAfterchangedYearOrMonth(changeYear, changeMonth, model)
-    const afterSetDays = setSelectedDays(days, dayFormat)
+    const specialDays = resetCalendarFromSpecialDay(days, day.full, value)
+    const { changeYear, changeMonth, afterDays } = specialDays
     this.setState({
-      days: afterSetDays,
+      days: afterDays,
       year: changeYear === _ ? year : changeYear,
       month: changeMonth === _ ? month : changeMonth,
-      value: dayFormat,
-    }, () => {
-      callback()
-    })
-  }
-
-  onSelectDay = day => {
-    const { days, value } = this.state
-    if (!isInCurrentMonth(day.full, value)) {
-      const year = day.full.substring(0, 4)
-      const month = day.full.substring(5, 7)
-      /* eslint-disable no-underscore-dangle */
-      this._onChangeYearOrMonth(year, month, () => this.onModalClose(), day.full)
-    } else {
-      const afterSetDays = setSelectedDays(days, day.full)
-      this.setState({ value: day.full, days: afterSetDays }, () => this.onModalClose())
-    }
+      value: day.full,
+    }, () => this._selectDayCallback(day.full))
   }
 
   onSelectToday = today => {
-    const { days } = this.state
+    const { days, value } = this.state
     let renderDays = days
-    if (!isInCurrentMonth(today)) {
+    if (!isInCurrentMonth(today, value)) {
       // 不是在【今天】这个月份,需要重新换数据源
       renderDays = initialData.days
     }
 
     const afterSetDays = setSelectedDays(renderDays, today)
-    this.setState({ value: today, days: afterSetDays }, () => this.onModalClose())
+    this.setState({ value: today, days: afterSetDays },
+      () => this._selectDayCallback(today))
+  }
+
+  _onChangeYearOrMonth = (changeYear, changeMonth) => {
+    const { model, year, month } = this.state
+    const days = getDaysAfterchangedYearOrMonth(changeYear, changeMonth, model)
+    this.setState({
+      days: days,
+      year: changeYear === _ ? year : changeYear,
+      month: changeMonth === _ ? month : changeMonth,
+    }, () => {
+      // todo bug
+      this.forceUpdate()
+    })
   }
 
   onPrevMonth = () => {
@@ -159,11 +160,11 @@ class DatePicker extends Component {
 
   onNextYear = () => {
     const { year } = this.state
-    this._onChangeYearOrMonth(year + 1, _)
+    this._onChangeYearOrMonth(+year + 1, _)
   }
 
   render() {
-    const { inline } = this.props
+    const { inline, placeholder } = this.props
     const { value, showModal } = this.state
 
     return (
@@ -174,7 +175,7 @@ class DatePicker extends Component {
         >
           <input
             type="text"
-            placeholder="请选择日期"
+            placeholder={placeholder}
             className={Styles.input}
             value={value}
             onChange={e => this.onInputChange(e)}
@@ -192,6 +193,7 @@ class DatePicker extends Component {
           value={
             {
               ...this.state,
+              ...this.props,
               onSelectDay: this.onSelectDay,
               onSelectToday: this.onSelectToday,
               onChangeModel: this.onChangeModel,
@@ -215,6 +217,7 @@ class DatePicker extends Component {
 
 DatePicker.defaultProps = {
   inline: false,
+  placeholder: INPUT_DEFAULT_PLACEHOLDER,
   defaultDate: getDateFormatFromSepecificDate(),
   year: getCurrentYear(),
   month: getCurrentMonth(),
@@ -222,9 +225,11 @@ DatePicker.defaultProps = {
 
 DatePicker.propTypes = {
   inline: PropTypes.bool,
+  placeholder: PropTypes.string,
   defaultDate: PropTypes.string,
   year: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
   month: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
+  onSelectDate: PropTypes.func.isRequired,
 }
 
 export default DatePicker

+ 2 - 2
src/components/input/Input.js

@@ -16,13 +16,13 @@ class Input extends React.Component {
     return (
       <DateContext.Consumer>
         {
-          ({ value, onInputChange }) => (
+          ({ value, placeholder, onInputChange }) => (
             <div className={Styles.wrapper}>
               <input
                 ref={this.textInput}
                 className={Styles.input}
                 type="text"
-                placeholder="请选择日期"
+                placeholder={placeholder}
                 value={value}
                 onChange={e => onInputChange(e)}
               />

+ 2 - 0
src/const/index.js

@@ -8,3 +8,5 @@ export const noop = () => {}
 export const PREV_DAY = 'PREV_DAY'
 export const NEXT_DAY = 'NEXT_DAY'
 export const CURRENT_DAY = 'CURRENT_DAY'
+
+export const INPUT_DEFAULT_PLACEHOLDER = '请选择日期'

+ 19 - 0
src/helper.js

@@ -140,3 +140,22 @@ export const getDaysAfterchangedYearOrMonth = (year = getCurrentYear(),
 export const isInCurrentMonth = (date, current = getCurrentDate()) => (
   date.substring(0, 7) === current.substring(0, 7)
 )
+
+export const resetCalendarFromSpecialDay = (originDays, date,
+  current = getCurrentDate(), model = CHINESE_MODEL) => {
+  let days = originDays
+  if (!isInCurrentMonth(date, current)) {
+    const year = date.substring(0, 4)
+    const month = date.substring(5, 7)
+    days = getDaysAfterchangedYearOrMonth(year, month, model)
+    const afterDays = setSelectedDays(days, date)
+    return {
+      afterDays: afterDays,
+      changeYear: year,
+      changeMonth: month,
+    }
+  }
+
+  const afterDays = setSelectedDays(days, date)
+  return { afterDays }
+}

+ 1 - 5
src/index.js

@@ -1,8 +1,4 @@
-
-import React from 'react'
-import ReactDOM from 'react-dom'
 import DatePicker from './components/index/DatePicker'
 import './styles/index.css'
 
-const App = () => <DatePicker />
-ReactDOM.render(<App />, document.getElementById('container'))
+export default DatePicker

+ 14 - 14
src/utils/date.js

@@ -14,6 +14,18 @@ export const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || (year
 export const trimStr = str => str.replace(/^\s*/, '').replace(/\s*$/, '')
 
 /**
+ * 格式化月份或者天数
+ * @param {String} dateStr 月份或者天数
+ */
+export const formatMonthOrDay = dateStr => {
+  if ((`${dateStr}`).length === 2) {
+    return dateStr
+  }
+
+  return `0${dateStr}`
+}
+
+/**
  * 获取当前年份
  */
 export const getCurrentYear = () => new Date().getFullYear()
@@ -21,12 +33,12 @@ export const getCurrentYear = () => new Date().getFullYear()
 /**
  * 获取当前月份
  */
-export const getCurrentMonth = () => new Date().getMonth() + 1
+export const getCurrentMonth = () => formatMonthOrDay(new Date().getMonth() + 1)
 
 /**
  * 获取当前天数
  */
-export const getCurrentDay = () => new Date().getDate()
+export const getCurrentDay = () => formatMonthOrDay(new Date().getDate())
 
 /**
  * 获取当前年份格式
@@ -34,18 +46,6 @@ export const getCurrentDay = () => new Date().getDate()
 export const getCurrentDate = () => `${getCurrentYear()}-${getCurrentMonth()}-${getCurrentDay()}`
 
 /**
- * 格式化月份或者天数
- * @param {String} dateStr 月份或者天数
- */
-export const formatMonthOrDay = dateStr => {
-  if ((`${dateStr}`).length === 2) {
-    return dateStr
-  }
-
-  return `0${dateStr}`
-}
-
-/**
  * 格式化日期
  * @param {String} date 日期
  */

+ 1 - 1
webpack/webpack.config.dev.js

@@ -7,7 +7,7 @@ const projectPath = path.resolve(__dirname, '../')
 module.exports = {
   mode: 'development',
   devtool: 'eval-source-map',
-  entry: path.resolve(projectPath, 'src/index.js'),
+  entry: path.resolve(projectPath, 'src/app.js'),
   output: {
     path: path.resolve(__dirname, 'dist'),
     filename: 'bundle.js',

+ 2 - 2
webpack/webpack.config.prod.js

@@ -6,7 +6,7 @@ const projectPath = path.resolve(__dirname, '../')
 
 module.exports = {
   mode: 'production',
-  entry: './src/index.js',
+  entry: './src/app.js',
   output: {
     path: path.resolve(__dirname, '../dist'),
     filename: '[name]-bundle-[hash:8].js',
@@ -51,7 +51,7 @@ module.exports = {
   plugins: [
     new MiniCssExtractPlugin({
       filename: '[name].[hash].css',
-      chunkFilename: '[id].[hash:base64:5].css',
+      chunkFilename: '[id].[hash].css',
     }),
     new HtmlWebpackPlugin({
       title: 'Datepicker',