Browse Source

style: 统一代码格式和样式

- 修复 SCSS 文件中的空格和格式问题
- 移除无用的导入和空行
- 统一字符串引号为单引号
- 修复 TypeScript 文件中的类型导入和导出格式
- 调整 JSON 文件格式和缩进
- 修复 WXML 中的条件渲染和属性绑定
- 优化组件样式和布局
- 统一日期显示格式
- 修复相机组件导航栏和示例显示问题
- 添加缺失的分号
- 优化弹出框样式和交互
dev
kola-web 1 week ago
parent
commit
5e454ce295
  1. 43
      src/components/calendar/core.js
  2. 2
      src/components/calendar/helper.js
  3. 2
      src/components/calendar/index.d.ts
  4. 97
      src/components/calendar/index.js
  5. 2
      src/components/calendar/index.json
  6. 122
      src/components/calendar/plugins/holidays/holidays-map.js
  7. 2
      src/components/calendar/plugins/holidays/index.d.ts
  8. 86
      src/components/calendar/plugins/holidays/index.js
  9. 2
      src/components/calendar/plugins/index.d.ts
  10. 11
      src/components/calendar/plugins/index.js
  11. 116
      src/components/calendar/plugins/preset/base.js
  12. 30
      src/components/calendar/plugins/preset/get-calendar-data.js
  13. 2
      src/components/calendar/plugins/preset/index.d.ts
  14. 2
      src/components/calendar/plugins/preset/index.js
  15. 2
      src/components/calendar/plugins/selectable.d.ts
  16. 104
      src/components/calendar/plugins/selectable.js
  17. 662
      src/components/calendar/plugins/solarLunar/convertSolarLunar.js
  18. 2
      src/components/calendar/plugins/solarLunar/index.d.ts
  19. 29
      src/components/calendar/plugins/solarLunar/index.js
  20. 126
      src/components/calendar/plugins/time-range.js
  21. 2
      src/components/calendar/plugins/todo.d.ts
  22. 56
      src/components/calendar/plugins/todo.js
  23. 156
      src/components/calendar/plugins/week.js
  24. 47
      src/components/calendar/render.js
  25. 290
      src/components/calendar/utils/index.js
  26. 18
      src/components/calendar/utils/logger.js
  27. 17
      src/components/calendar/utils/wxData.js
  28. 148
      src/components/customPoster/README.md
  29. 88
      src/components/customPoster/index.js
  30. 1968
      src/components/customPoster/wxml2canvas/index.js
  31. 148
      src/components/customTable/README.md
  32. 203
      src/components/customTable/index.js
  33. 1966
      src/components/customTable/wxml2canvas/index.js
  34. 216
      src/components/ec-canvas/ec-canvas.js
  35. 2
      src/components/ec-canvas/ec-canvas.json
  36. 66
      src/components/ec-canvas/wx-canvas.js
  37. 149
      src/components/freeAudio/index.js
  38. 2
      src/components/image-merge/index.json
  39. 6
      src/components/loginNavbar/index.ts
  40. 6
      src/components/navbar/index.ts
  41. 5
      src/components/noteImagePreview/index.json
  42. 3
      src/components/noteImagePreview/index.ts
  43. 8
      src/components/noteImagePreview/index.wxml
  44. 6
      src/components/pageNavbar/index.ts
  45. 10
      src/components/pickerArea/index.scss
  46. 52
      src/components/popup/index.scss
  47. 14
      src/components/popup/index.wxml
  48. 209
      src/components/star/index.ts
  49. 8
      src/components/text-expandsion/index.scss
  50. 50
      src/components/timeOut/index.ts
  51. 72
      src/components/toast/index.ts
  52. 87
      src/components/uploadFile/index.ts
  53. 28
      src/components/viewFile/index.js
  54. 2
      src/components/viewFile/index.json
  55. 7
      src/components/viewVideo/index.scss
  56. 228
      src/components/zd-navBar/navBar.js
  57. 2
      src/components/zd-navBar/navBar.scss
  58. 164
      src/components/zdUploadFile/index.js
  59. 2
      src/doc/pages/doc1/index.scss
  60. 6
      src/doc/pages/doc1/index.ts
  61. 2
      src/doc/pages/doc2/index.scss
  62. 5184
      src/gift/compontnts/echart/echarts.js
  63. 2
      src/pages/d_invite/index.scss
  64. 8
      src/pages/d_noteDetail/index.wxml
  65. 10
      src/pages/d_noteDiff/index.wxml
  66. 6
      src/pages/d_noteDiffData/index.wxml
  67. 2
      src/pages/d_noteDiffEdit/index.ts
  68. 2
      src/pages/d_noteDiffEdit/index.wxml
  69. 4
      src/pages/d_noteList/index.wxml
  70. 4
      src/pages/d_patientDetail/index.wxml
  71. 2
      src/pages/d_patientHormones/index.ts
  72. 4
      src/pages/d_userInfo/index.scss
  73. 13
      src/pages/d_userInfo/index.ts
  74. 2
      src/pages/information/index.json
  75. 7
      src/pages/informationDetail/index.ts
  76. 2
      src/pages/login/index.scss
  77. 42
      src/pages/message/index.ts
  78. 2
      src/pages/start/index.scss
  79. 8
      src/pages/webview/index.ts
  80. 3
      src/patient/components/camera/index.json
  81. 3
      src/patient/components/camera/index.scss
  82. 7
      src/patient/components/camera/index.ts
  83. 9
      src/patient/components/camera/index.wxml
  84. 2
      src/patient/pages/cancellation/index.scss
  85. 34
      src/patient/pages/cancellation/index.ts
  86. 2
      src/patient/pages/certPending/index.scss
  87. 32
      src/patient/pages/certPending/index.ts
  88. 2
      src/patient/pages/certReslove/index.scss
  89. 81
      src/patient/pages/changePhone/index.ts
  90. 89
      src/patient/pages/changeUser/index.ts
  91. 6
      src/patient/pages/comIns/index.ts
  92. 2
      src/patient/pages/doctor/index.json
  93. 4
      src/patient/pages/doctor/siteShare/index.ts
  94. 6
      src/patient/pages/drugRecord/index.scss
  95. 3
      src/patient/pages/drugRecord/index.ts
  96. 1
      src/patient/pages/family/index.ts
  97. 2
      src/patient/pages/familyList/index.json
  98. 61
      src/patient/pages/familyList/index.ts
  99. 12
      src/patient/pages/familyScan/index.scss
  100. 74
      src/patient/pages/familyScan/index.ts
  101. Some files were not shown because too many files have changed in this diff Show More

43
src/components/calendar/core.js

@ -10,7 +10,7 @@ function calculateEmptyGrids(year, month, config) {
const nextMonthGrids = calculateNextMonthGrids(year, month, config) const nextMonthGrids = calculateNextMonthGrids(year, month, config)
return { return {
prevMonthGrids, prevMonthGrids,
nextMonthGrids nextMonthGrids,
} }
} }
@ -20,13 +20,14 @@ function calculateEmptyGrids(year, month, config) {
* @param {number} month 月份 * @param {number} month 月份
*/ */
function calculatePrevMonthGrids(year, month, config) { function calculatePrevMonthGrids(year, month, config) {
let emptyGrids = [] const emptyGrids = []
const prevMonthDays = dateUtil.getDatesCountOfMonth(year, month - 1) const prevMonthDays = dateUtil.getDatesCountOfMonth(year, month - 1)
let firstDayOfWeek = dateUtil.firstDayOfWeek(year, month) let firstDayOfWeek = dateUtil.firstDayOfWeek(year, month)
if (config.firstDayOfWeek === 'Mon') { if (config.firstDayOfWeek === 'Mon') {
if (firstDayOfWeek === 0) { if (firstDayOfWeek === 0) {
firstDayOfWeek = 6 firstDayOfWeek = 6
} else { }
else {
firstDayOfWeek -= 1 firstDayOfWeek -= 1
} }
} }
@ -37,12 +38,13 @@ function calculatePrevMonthGrids(year, month, config) {
for (let i = prevMonthDays; i > len; i--) { for (let i = prevMonthDays; i > len; i--) {
if (onlyShowCurrentMonth) { if (onlyShowCurrentMonth) {
emptyGrids.push('') emptyGrids.push('')
} else { }
else {
const week = dateUtil.getDayOfWeek(+year, +month, i) const week = dateUtil.getDayOfWeek(+year, +month, i)
emptyGrids.push({ emptyGrids.push({
...YMInfo, ...YMInfo,
date: i, date: i,
week week,
}) })
} }
} }
@ -61,19 +63,24 @@ function calculateExtraEmptyDate(year, month, config) {
let extDate = 0 let extDate = 0
if (+month === 2) { if (+month === 2) {
extDate += 7 extDate += 7
let firstDayofMonth = dateUtil.getDayOfWeek(year, month, 1) const firstDayofMonth = dateUtil.getDayOfWeek(year, month, 1)
if (config.firstDayOfWeek === 'Mon') { if (config.firstDayOfWeek === 'Mon') {
if (+firstDayofMonth === 1) extDate += 7 if (+firstDayofMonth === 1)
} else { extDate += 7
if (+firstDayofMonth === 0) extDate += 7 }
else {
if (+firstDayofMonth === 0)
extDate += 7
} }
} else { }
let firstDayofMonth = dateUtil.getDayOfWeek(year, month, 1) else {
const firstDayofMonth = dateUtil.getDayOfWeek(year, month, 1)
if (config.firstDayOfWeek === 'Mon') { if (config.firstDayOfWeek === 'Mon') {
if (firstDayofMonth !== 0 && firstDayofMonth < 6) { if (firstDayofMonth !== 0 && firstDayofMonth < 6) {
extDate += 7 extDate += 7
} }
} else { }
else {
if (firstDayofMonth <= 5) { if (firstDayofMonth <= 5) {
extDate += 7 extDate += 7
} }
@ -87,13 +94,14 @@ function calculateExtraEmptyDate(year, month, config) {
* @param {number} month 月份 * @param {number} month 月份
*/ */
function calculateNextMonthGrids(year, month, config) { function calculateNextMonthGrids(year, month, config) {
let emptyGrids = [] const emptyGrids = []
const datesCount = dateUtil.getDatesCountOfMonth(year, month) const datesCount = dateUtil.getDatesCountOfMonth(year, month)
let lastDayWeek = dateUtil.getDayOfWeek(year, month, datesCount) let lastDayWeek = dateUtil.getDayOfWeek(year, month, datesCount)
if (config.firstDayOfWeek === 'Mon') { if (config.firstDayOfWeek === 'Mon') {
if (lastDayWeek === 0) { if (lastDayWeek === 0) {
lastDayWeek = 6 lastDayWeek = 6
} else { }
else {
lastDayWeek -= 1 lastDayWeek -= 1
} }
} }
@ -107,12 +115,13 @@ function calculateNextMonthGrids(year, month, config) {
const week = dateUtil.getDayOfWeek(+year, +month, i) const week = dateUtil.getDayOfWeek(+year, +month, i)
if (onlyShowCurrentMonth) { if (onlyShowCurrentMonth) {
emptyGrids.push('') emptyGrids.push('')
} else { }
else {
emptyGrids.push({ emptyGrids.push({
id: i - 1, id: i - 1,
...YMInfo, ...YMInfo,
date: i, date: i,
week: week || 7 week: week || 7,
}) })
} }
} }
@ -138,7 +147,7 @@ export function calcJumpData({ dateInfo, config, component }) {
curMonth: month, curMonth: month,
curDate: date, curDate: date,
dates: calculateCurrentMonthDates(year, month), dates: calculateCurrentMonthDates(year, month),
...emptyGrids ...emptyGrids,
} }
return calendar return calendar
} }

2
src/components/calendar/helper.js

@ -7,6 +7,6 @@ export function calcTargetYMInfo() {
prev_month: dateUtil.getPrevMonthInfo, prev_month: dateUtil.getPrevMonthInfo,
next_month: dateUtil.getNextMonthInfo, next_month: dateUtil.getNextMonthInfo,
prev_year: dateUtil.getPrevYearInfo, prev_year: dateUtil.getPrevYearInfo,
next_year: dateUtil.getNextYearInfo next_year: dateUtil.getNextYearInfo,
} }
} }

2
src/components/calendar/index.d.ts vendored

@ -1 +1 @@
export {}; export {}

97
src/components/calendar/index.js

@ -1,24 +1,24 @@
import plugins from './plugins/index'
import { calcJumpData } from './core' import { calcJumpData } from './core'
import { renderCalendar } from './render'
import { calcTargetYMInfo } from './helper' import { calcTargetYMInfo } from './helper'
import { dateUtil, calendarGesture, logger } from './utils/index' import plugins from './plugins/index'
import { renderCalendar } from './render'
import { calendarGesture, dateUtil, logger } from './utils/index'
Component({ Component({
options: { options: {
styleIsolation: 'apply-shared', styleIsolation: 'apply-shared',
multipleSlots: true // 在组件定义时的选项中启用多slot支持 multipleSlots: true, // 在组件定义时的选项中启用多slot支持
}, },
properties: { properties: {
config: { config: {
type: Object, type: Object,
value: {} value: {},
} },
}, },
lifetimes: { lifetimes: {
attached: function() { attached() {
this.initComp() this.initComp()
} },
}, },
methods: { methods: {
initComp() { initComp() {
@ -30,7 +30,7 @@ Component({
const calendarConfig = this.properties.config || {} const calendarConfig = this.properties.config || {}
if (calendarConfig.disableMode && !calendarConfig.disableMode.date) { if (calendarConfig.disableMode && !calendarConfig.disableMode.date) {
calendarConfig.disableMode.date = dateUtil.toTimeStr( calendarConfig.disableMode.date = dateUtil.toTimeStr(
dateUtil.todayFMD() dateUtil.todayFMD(),
) )
} }
return calendarConfig return calendarConfig
@ -42,27 +42,29 @@ Component({
const dateInfo = defaultDate.split('-') const dateInfo = defaultDate.split('-')
if (dateInfo.length < 3) { if (dateInfo.length < 3) {
return logger.warn('defaultDate配置格式应为: 2018-4-2 或 2018-04-02') return logger.warn('defaultDate配置格式应为: 2018-4-2 或 2018-04-02')
} else { }
else {
date = { date = {
year: +dateInfo[0], year: +dateInfo[0],
month: +dateInfo[1], month: +dateInfo[1],
date: +dateInfo[2] date: +dateInfo[2],
} }
} }
} }
const waitRenderData = calcJumpData({ const waitRenderData = calcJumpData({
dateInfo: date, dateInfo: date,
config config,
}) })
const timestamp = dateUtil.todayTimestamp() const timestamp = dateUtil.todayTimestamp()
if (config.autoChoosedWhenJump) { if (config.autoChoosedWhenJump) {
const target = waitRenderData.dates.filter( const target = waitRenderData.dates.filter(
item => dateUtil.toTimeStr(item) === dateUtil.toTimeStr(date) item => dateUtil.toTimeStr(item) === dateUtil.toTimeStr(date),
) )
if (target && target.length) { if (target && target.length) {
if (!waitRenderData.selectedDates) { if (!waitRenderData.selectedDates) {
waitRenderData.selectedDates = target waitRenderData.selectedDates = target
} else { }
else {
waitRenderData.selectedDates.push(target[0]) waitRenderData.selectedDates.push(target[0])
} }
} }
@ -70,7 +72,7 @@ Component({
return { return {
...waitRenderData, ...waitRenderData,
todayTimestamp: timestamp, todayTimestamp: timestamp,
weeksCh: dateUtil.getWeekHeader(config.firstDayOfWeek) weeksCh: dateUtil.getWeekHeader(config.firstDayOfWeek),
} }
}, },
setConfig(config) { setConfig(config) {
@ -80,21 +82,23 @@ Component({
config.theme = config.theme || 'default' config.theme = config.theme || 'default'
this.setData( this.setData(
{ {
config config,
}, },
() => { () => {
for (let plugin of plugins.installed) { for (const plugin of plugins.installed) {
const [, p] = plugin const [, p] = plugin
if (typeof p.install === 'function') { if (typeof p.install === 'function') {
p.install(this) p.install(this)
} }
if (typeof p.methods === 'function') { if (typeof p.methods === 'function') {
const methods = p.methods(this) const methods = p.methods(this)
for (let fnName in methods) { for (const fnName in methods) {
if (fnName.startsWith('__')) continue if (fnName.startsWith('__'))
continue
const fn = methods[fnName] const fn = methods[fnName]
if (typeof fn === 'function') { if (typeof fn === 'function') {
if (!this.calendar) this.calendar = {} if (!this.calendar)
this.calendar = {}
this.calendar[fnName] = fn this.calendar[fnName] = fn
} }
} }
@ -102,25 +106,26 @@ Component({
} }
const initData = this.initCalendar(config) const initData = this.initCalendar(config)
renderCalendar.call(this, initData, config) renderCalendar.call(this, initData, config)
} },
) )
}, },
tapDate(e) { tapDate(e) {
const { info } = e.currentTarget.dataset const { info } = e.currentTarget.dataset
const { date, disable } = info || {} const { date, disable } = info || {}
if (disable || !date) return if (disable || !date)
return
const { calendar, config } = this.data const { calendar, config } = this.data
let calendarData = calendar let calendarData = calendar
let calendarConfig = config let calendarConfig = config
if (config.takeoverTap) { if (config.takeoverTap) {
return this.triggerEvent('takeoverTap', info) return this.triggerEvent('takeoverTap', info)
} }
for (let plugin of plugins.installed) { for (const plugin of plugins.installed) {
const [, p] = plugin const [, p] = plugin
if (typeof p.onTapDate === 'function') { if (typeof p.onTapDate === 'function') {
const { const {
calendarData: __calendarData, calendarData: __calendarData,
calendarConfig: __calendarConfig calendarConfig: __calendarConfig,
} = p.onTapDate(info, calendarData, calendarConfig) } = p.onTapDate(info, calendarData, calendarConfig)
calendarData = __calendarData calendarData = __calendarData
calendarConfig = __calendarConfig calendarConfig = __calendarConfig
@ -141,7 +146,7 @@ Component({
this.swipeLock = true this.swipeLock = true
this.setData({ this.setData({
'gesture.startX': startX, 'gesture.startX': startX,
'gesture.startY': startY 'gesture.startY': startY,
}) })
}, },
/** /**
@ -151,7 +156,8 @@ Component({
calendarTouchmove(e) { calendarTouchmove(e) {
const { gesture } = this.data const { gesture } = this.data
const { preventSwipe } = this.properties.config const { preventSwipe } = this.properties.config
if (!this.swipeLock || preventSwipe) return if (!this.swipeLock || preventSwipe)
return
if (calendarGesture.isLeft(gesture, e.touches[0])) { if (calendarGesture.isLeft(gesture, e.touches[0])) {
this.handleSwipe('left') this.handleSwipe('left')
this.swipeLock = false this.swipeLock = false
@ -164,7 +170,7 @@ Component({
calendarTouchend(e) { calendarTouchend(e) {
this.setData({ this.setData({
'calendar.leftSwipe': 0, 'calendar.leftSwipe': 0,
'calendar.rightSwipe': 0 'calendar.rightSwipe': 0,
}) })
}, },
handleSwipe(direction) { handleSwipe(direction) {
@ -173,15 +179,15 @@ Component({
swipeKey = 'calendar.rightSwipe' swipeKey = 'calendar.rightSwipe'
} }
this.setData({ this.setData({
[swipeKey]: 1 [swipeKey]: 1,
}) })
const { calendar } = this.data const { calendar } = this.data
let calendarData = calendar const calendarData = calendar
const { curYear, curMonth } = calendarData const { curYear, curMonth } = calendarData
const getMonthInfo = calcTargetYMInfo()[direction] const getMonthInfo = calcTargetYMInfo()[direction]
const target = getMonthInfo({ const target = getMonthInfo({
year: +curYear, year: +curYear,
month: +curMonth month: +curMonth,
}) })
target.direction = direction target.direction = direction
this.renderCalendar(target) this.renderCalendar(target)
@ -193,7 +199,7 @@ Component({
const getMonthInfo = calcTargetYMInfo()[type] const getMonthInfo = calcTargetYMInfo()[type]
const target = getMonthInfo({ const target = getMonthInfo({
year: +curYear, year: +curYear,
month: +curMonth month: +curMonth,
}) })
target.direction = type target.direction = type
this.renderCalendar(target) this.renderCalendar(target)
@ -201,7 +207,7 @@ Component({
renderCalendar(target) { renderCalendar(target) {
let { calendar: calendarData, config } = this.data let { calendar: calendarData, config } = this.data
const { curYear, curMonth } = calendarData || {} const { curYear, curMonth } = calendarData || {}
for (let plugin of plugins.installed) { for (const plugin of plugins.installed) {
const [, p] = plugin const [, p] = plugin
if (typeof p.onSwitchCalendar === 'function') { if (typeof p.onSwitchCalendar === 'function') {
calendarData = p.onSwitchCalendar(target, calendarData, this) calendarData = p.onSwitchCalendar(target, calendarData, this)
@ -215,44 +221,47 @@ Component({
this.triggerEvent(triggerEventName, { this.triggerEvent(triggerEventName, {
current: { current: {
year: +curYear, year: +curYear,
month: +curMonth month: +curMonth,
}, },
next: target next: target,
}) })
this.triggerEvent('onSwipe', { this.triggerEvent('onSwipe', {
current: { current: {
year: +curYear, year: +curYear,
month: +curMonth month: +curMonth,
}, },
next: target, next: target,
type: triggerEventName type: triggerEventName,
}) })
}) })
}, },
doubleClickJumpToToday() { doubleClickJumpToToday() {
const { multi, weekMode } = this.calendar.getCalendarConfig() || {} const { multi, weekMode } = this.calendar.getCalendarConfig() || {}
if (multi || weekMode) return if (multi || weekMode)
return
if (this.count === undefined) { if (this.count === undefined) {
this.count = 1 this.count = 1
} else { }
else {
this.count += 1 this.count += 1
} }
if (this.lastClick) { if (this.lastClick) {
const difference = new Date().getTime() - this.lastClick const difference = new Date().getTime() - this.lastClick
if ( if (
difference < 500 && difference < 500
this.count >= 2 && && this.count >= 2
typeof this.calendar.jump === 'function' && typeof this.calendar.jump === 'function'
) { ) {
const today = dateUtil.todayFMD() const today = dateUtil.todayFMD()
this.calendar.jump(today) this.calendar.jump(today)
} }
this.count = undefined this.count = undefined
this.lastClick = undefined this.lastClick = undefined
} else { }
else {
this.lastClick = new Date().getTime() this.lastClick = new Date().getTime()
} }
this.triggerEvent('jumpToToday') this.triggerEvent('jumpToToday')
} },
} },
}) })

2
src/components/calendar/index.json

@ -1,3 +1,3 @@
{ {
"component": true "component": true
} }

122
src/components/calendar/plugins/holidays/holidays-map.js

@ -14,38 +14,38 @@ export const festival = {
1: { 1: {
type: 'festival', type: 'festival',
name: '春节', name: '春节',
label: '春节' label: '春节',
}, },
8: { 8: {
type: 'festival', type: 'festival',
name: '腊八节', name: '腊八节',
label: '腊八' label: '腊八',
}, },
15: { 15: {
type: 'festival', type: 'festival',
name: '元宵节', name: '元宵节',
label: '元宵' label: '元宵',
} },
}, },
7: { 7: {
7: { 7: {
type: 'festival', type: 'festival',
name: '七夕节', name: '七夕节',
label: '七夕' label: '七夕',
}, },
15: { 15: {
type: 'festival', type: 'festival',
name: '中元节', name: '中元节',
label: '中元节' label: '中元节',
} },
}, },
9: { 9: {
9: { 9: {
type: 'festival', type: 'festival',
name: '重阳节', name: '重阳节',
label: '重阳节' label: '重阳节',
} },
} },
}, },
// 阳历固定日期节日 // 阳历固定日期节日
solar: { solar: {
@ -53,160 +53,160 @@ export const festival = {
14: { 14: {
type: 'festival', type: 'festival',
name: '情人节', name: '情人节',
label: '情人节' label: '情人节',
} },
}, },
3: { 3: {
12: { 12: {
type: 'festival', type: 'festival',
name: '植树节', name: '植树节',
label: '植树节' label: '植树节',
} },
}, },
4: { 4: {
1: { 1: {
type: 'festival', type: 'festival',
name: '愚人节', name: '愚人节',
label: '愚人节' label: '愚人节',
}, },
5: { 5: {
type: 'festival', type: 'festival',
name: '清明节', name: '清明节',
label: '清明节' label: '清明节',
} },
}, },
5: { 5: {
1: { 1: {
type: 'festival', type: 'festival',
name: '劳动节', name: '劳动节',
label: '劳动节' label: '劳动节',
} },
}, },
6: { 6: {
1: { 1: {
type: 'festival', type: 'festival',
name: '儿童节', name: '儿童节',
label: '儿童节' label: '儿童节',
} },
}, },
7: { 7: {
1: { 1: {
type: 'festival', type: 'festival',
name: '建党节', name: '建党节',
label: '建党节' label: '建党节',
} },
}, },
8: { 8: {
1: { 1: {
type: 'festival', type: 'festival',
name: '建军节', name: '建军节',
label: '建军节' label: '建军节',
} },
}, },
9: { 9: {
10: { 10: {
type: 'festival', type: 'festival',
name: '教师节', name: '教师节',
label: '教师节' label: '教师节',
} },
}, },
10: { 10: {
1: { 1: {
type: 'festival', type: 'festival',
name: '国庆节', name: '国庆节',
label: '国庆节' label: '国庆节',
} },
}, },
12: { 12: {
25: { 25: {
type: 'festival', type: 'festival',
name: '圣诞节', name: '圣诞节',
label: '圣诞节' label: '圣诞节',
} },
} },
} },
} }
export const holidays = { export const holidays = {
2020: { 2020: {
1: { 1: {
1: { '1': {
type: 'holiday', type: 'holiday',
name: '元旦', name: '元旦',
label: '休' label: '休',
}, },
19: { '19': {
type: 'work', type: 'work',
name: '调班', name: '调班',
label: '班' label: '班',
}, },
'24-30': { '24-30': {
type: 'holiday', type: 'holiday',
name: '春节', name: '春节',
label: '休' label: '休',
} },
}, },
2: { 2: {
1: { 1: {
type: 'work', type: 'work',
name: '调班', name: '调班',
label: '班' label: '班',
} },
}, },
4: { 4: {
'4-6': { '4-6': {
type: 'holiday', type: 'holiday',
name: '清明节', name: '清明节',
label: '休' label: '休',
}, },
26: { '26': {
type: 'work', type: 'work',
name: '调班', name: '调班',
label: '班' label: '班',
} },
}, },
5: { 5: {
'1-5': { '1-5': {
type: 'holiday', type: 'holiday',
name: '劳动节', name: '劳动节',
label: '休' label: '休',
}, },
9: { '9': {
type: 'work', type: 'work',
name: '调班', name: '调班',
label: '班' label: '班',
} },
}, },
6: { 6: {
'25-27': { '25-27': {
type: 'holiday', type: 'holiday',
name: '端午节', name: '端午节',
label: '休' label: '休',
}, },
28: { '28': {
type: 'work', type: 'work',
name: '调班', name: '调班',
label: '班' label: '班',
} },
}, },
9: { 9: {
27: { 27: {
type: 'work', type: 'work',
name: '调班', name: '调班',
label: '班' label: '班',
} },
}, },
10: { 10: {
'1-8': { '1-8': {
type: 'holiday', type: 'holiday',
name: '国庆节/中秋节', name: '国庆节/中秋节',
label: '休' label: '休',
}, },
10: { '10': {
type: 'work', type: 'work',
name: '调班', name: '调班',
label: '班' label: '班',
} },
} },
} },
} }

2
src/components/calendar/plugins/holidays/index.d.ts vendored

@ -1 +1 @@
export {}; export {}

86
src/components/calendar/plugins/holidays/index.js

@ -6,8 +6,8 @@
* @Last Modified time: 2020-10-16 17:34:13 * @Last Modified time: 2020-10-16 17:34:13
*/ */
import { holidays, festival } from './holidays-map'
import { dateUtil, getCalendarData, logger } from '../../utils/index' import { dateUtil, getCalendarData, logger } from '../../utils/index'
import { festival, holidays } from './holidays-map'
/** /**
* 当前是否在休假期内 * 当前是否在休假期内
@ -20,21 +20,21 @@ function inHolidays({ year, month }, { start, end, current }) {
const startTimestamp = getTimeStamp({ const startTimestamp = getTimeStamp({
year, year,
month, month,
date: start date: start,
}) })
const endTimestamp = getTimeStamp({ const endTimestamp = getTimeStamp({
year, year,
month, month,
date: end date: end,
}) })
const currentDateTimestamp = getTimeStamp({ const currentDateTimestamp = getTimeStamp({
year, year,
month, month,
date: current date: current,
}) })
if ( if (
currentDateTimestamp >= startTimestamp && currentDateTimestamp >= startTimestamp
currentDateTimestamp <= endTimestamp && currentDateTimestamp <= endTimestamp
) { ) {
return true return true
} }
@ -49,13 +49,15 @@ function addSpecialFestival(date, component) {
const info = { const info = {
type: 'festival', type: 'festival',
name: '除夕', name: '除夕',
label: '除夕' label: '除夕',
} }
if (lMonth === 12) { if (lMonth === 12) {
if (!festival.lunar['12']) festival.lunar['12'] = {} if (!festival.lunar['12'])
festival.lunar['12'] = {}
if (convertlLunar2Solar(`${lYear}-12-30`) === -1) { if (convertlLunar2Solar(`${lYear}-12-30`) === -1) {
festival.lunar['12']['29'] = info festival.lunar['12']['29'] = info
} else { }
else {
festival.lunar['12']['30'] = info festival.lunar['12']['30'] = info
} }
} }
@ -63,8 +65,8 @@ function addSpecialFestival(date, component) {
/** /**
* 是否匹配到节日 * 是否匹配到节日
* @param {object} [dateInfo={}] * @param {object} [dateInfo]
* @param {object} [component={}] * @param {object} [component]
* @returns {object|boolean} 匹配到的节日数据或者false * @returns {object|boolean} 匹配到的节日数据或者false
*/ */
function hasFestivalDate(dateInfo = {}, component = {}) { function hasFestivalDate(dateInfo = {}, component = {}) {
@ -78,19 +80,22 @@ function hasFestivalDate(dateInfo = {}, component = {}) {
if (!festivalDate) { if (!festivalDate) {
const festivalOfMonth = festival.lunar[lMonth] || {} const festivalOfMonth = festival.lunar[lMonth] || {}
const festivalDateKey = Object.keys(festivalOfMonth).find(item => const festivalDateKey = Object.keys(festivalOfMonth).find(item =>
item.match(new RegExp(`\\b${lDay}\\b`)) item.match(new RegExp(`\\b${lDay}\\b`)),
) )
if (!festivalDateKey) { if (!festivalDateKey) {
festivalDate = false festivalDate = false
} else { }
else {
const festivalInfo = festival.lunar[lMonth][festivalDateKey] const festivalInfo = festival.lunar[lMonth][festivalDateKey]
if (!festivalInfo) { if (!festivalInfo) {
festivalDate = false festivalDate = false
} else { }
else {
const { condition } = festivalInfo const { condition } = festivalInfo
if (typeof condition === 'function') { if (typeof condition === 'function') {
festivalDate = condition(lunarDateInfo) festivalDate = condition(lunarDateInfo)
} else { }
else {
festivalDate = false festivalDate = false
} }
} }
@ -106,23 +111,24 @@ export default () => {
beforeRender(calendarData = {}, calendarConfig = {}, component) { beforeRender(calendarData = {}, calendarConfig = {}, component) {
let { dates = [] } = calendarData let { dates = [] } = calendarData
if (calendarConfig.showHolidays || calendarConfig.showFestival) { if (calendarConfig.showHolidays || calendarConfig.showFestival) {
dates = dates.map(d => { dates = dates.map((d) => {
let item = { ...d } let item = { ...d }
const { year, month, date } = item const { year, month, date } = item
const holidaysOfMonth = const holidaysOfMonth
(holidays[year] && holidays[year][month]) || {} = (holidays[year] && holidays[year][month]) || {}
const holidayDate = holidaysOfMonth[date] const holidayDate = holidaysOfMonth[date]
if (holidayDate) { if (holidayDate) {
item = { item = {
...item, ...item,
...holidayDate ...holidayDate,
} }
} else { }
else {
const holidayKeys = Object.keys(holidaysOfMonth).filter(item => const holidayKeys = Object.keys(holidaysOfMonth).filter(item =>
item.includes('-') item.includes('-'),
) )
let target = '' let target = ''
for (let v of holidayKeys) { for (const v of holidayKeys) {
const [start, end] = v.split('-') const [start, end] = v.split('-')
if (+d.date >= +start && +d.date <= +end) { if (+d.date >= +start && +d.date <= +end) {
target = v target = v
@ -133,28 +139,29 @@ export default () => {
const isInHolidays = inHolidays( const isInHolidays = inHolidays(
{ {
year, year,
month month,
}, },
{ {
start, start,
end, end,
current: date current: date,
} },
) )
if (isInHolidays) { if (isInHolidays) {
item = { item = {
...item, ...item,
...holidaysOfMonth[target] ...holidaysOfMonth[target],
} }
} else if (calendarConfig.showFestival) { }
const { convertSolarLunar, convertlLunar2Solar } = else if (calendarConfig.showFestival) {
component.calendar || {} const { convertSolarLunar, convertlLunar2Solar }
= component.calendar || {}
if ( if (
typeof convertSolarLunar !== 'function' || typeof convertSolarLunar !== 'function'
typeof convertlLunar2Solar !== 'function' || typeof convertlLunar2Solar !== 'function'
) { ) {
return logger.warn( return logger.warn(
'农历节日显示需要引入农历插件(/component/v2/plugins/solarLunar)' '农历节日显示需要引入农历插件(/component/v2/plugins/solarLunar)',
) )
} }
addSpecialFestival(item, component) addSpecialFestival(item, component)
@ -162,7 +169,7 @@ export default () => {
if (festivalDate) { if (festivalDate) {
item = { item = {
...item, ...item,
...festivalDate ...festivalDate,
} }
} }
} }
@ -173,9 +180,9 @@ export default () => {
return { return {
calendarData: { calendarData: {
...calendarData, ...calendarData,
dates: dates dates,
}, },
calendarConfig calendarConfig,
} }
}, },
methods(component) { methods(component) {
@ -186,16 +193,17 @@ export default () => {
return this.methods(component).getHolidaysOfYear(curYear) return this.methods(component).getHolidaysOfYear(curYear)
}, },
getHolidaysOfYear(year) { getHolidaysOfYear(year) {
if (!year) return logger.warn('getHolidaysOfCurrentYear() 入参错误') if (!year)
return logger.warn('getHolidaysOfCurrentYear() 入参错误')
if (!holidays[year]) { if (!holidays[year]) {
logger.warn('未匹配到当前年份节假日信息,请自行补充') logger.warn('未匹配到当前年份节假日信息,请自行补充')
return { return {
err: 'not match' err: 'not match',
} }
} }
return holidays[year] return holidays[year]
} },
} }
} },
} }
} }

2
src/components/calendar/plugins/index.d.ts vendored

@ -1 +1 @@
export {}; export {}

11
src/components/calendar/plugins/index.js

@ -3,16 +3,17 @@ import preset from './preset/index'
export default { export default {
installed: [...preset], installed: [...preset],
use(plugin) { use(plugin) {
if (typeof plugin !== 'function') return if (typeof plugin !== 'function')
return
const info = plugin() || {} const info = plugin() || {}
const { name } = info const { name } = info
if ( if (
name && name
name !== 'methods' && && name !== 'methods'
!this.installed.some(p => p[0] === name) && !this.installed.some(p => p[0] === name)
) { ) {
this.installed.unshift([name, info]) this.installed.unshift([name, info])
} }
return this return this
} },
} }

116
src/components/calendar/plugins/preset/base.js

@ -4,15 +4,15 @@
* @Date: 2020-10-08 21:22:09* * @Date: 2020-10-08 21:22:09*
* @Last Modified by: drfu * @Last Modified by: drfu
* @Last Modified time: 2020-10-11 13:28:52 * @Last Modified time: 2020-10-11 13:28:52
* */ */
import { calcJumpData } from '../../core' import { calcJumpData } from '../../core'
import { renderCalendar } from '../../render' import { renderCalendar } from '../../render'
import { import {
dateUtil, dateUtil,
getCalendarConfig,
getCalendarData, getCalendarData,
setCalendarData, setCalendarData,
getCalendarConfig
} from '../../utils/index' } from '../../utils/index'
export default () => { export default () => {
@ -21,12 +21,12 @@ export default () => {
beforeRender(calendarData = {}, calendarConfig) { beforeRender(calendarData = {}, calendarConfig) {
const calendar = calendarData const calendar = calendarData
const { selectedDates = [], dates } = calendar const { selectedDates = [], dates } = calendar
let _dates = [...dates] const _dates = [...dates]
if (selectedDates.length) { if (selectedDates.length) {
const selectedDatesStr = selectedDates.map(date => const selectedDatesStr = selectedDates.map(date =>
dateUtil.toTimeStr(date) dateUtil.toTimeStr(date),
) )
_dates.forEach(date => { _dates.forEach((date) => {
const dateStr = dateUtil.toTimeStr(date) const dateStr = dateUtil.toTimeStr(date)
if (selectedDatesStr.includes(dateStr)) { if (selectedDatesStr.includes(dateStr)) {
date.choosed = true date.choosed = true
@ -36,21 +36,21 @@ export default () => {
return { return {
calendarData: { calendarData: {
...calendarData, ...calendarData,
dates: _dates dates: _dates,
}, },
calendarConfig calendarConfig,
} }
}, },
onTapDate(tapedDate, calendarData = {}, calendarConfig = {}) { onTapDate(tapedDate, calendarData = {}, calendarConfig = {}) {
const calendar = { const calendar = {
...calendarData ...calendarData,
} }
const dateIndex = dateUtil.findDateIndexInArray( const dateIndex = dateUtil.findDateIndexInArray(
tapedDate, tapedDate,
calendarData.dates calendarData.dates,
) )
const { multi, inverse } = calendarConfig const { multi, inverse } = calendarConfig
let dates = [...calendar.dates] const dates = [...calendar.dates]
const { selectedDates = [] } = calendar const { selectedDates = [] } = calendar
if (!multi) { if (!multi) {
let preSelectedDate = {} let preSelectedDate = {}
@ -61,7 +61,7 @@ export default () => {
if (!inverse && timeStr(preSelectedDate) === timeStr(tapedDate)) { if (!inverse && timeStr(preSelectedDate) === timeStr(tapedDate)) {
return calendar return calendar
} }
let _tapedDate = { ...tapedDate, choosed: !tapedDate.choosed } const _tapedDate = { ...tapedDate, choosed: !tapedDate.choosed }
dates[dateIndex] = _tapedDate dates[dateIndex] = _tapedDate
if (preSelectedDate.date) { if (preSelectedDate.date) {
@ -73,32 +73,35 @@ export default () => {
} }
if (dates[dateIndex].choosed) { if (dates[dateIndex].choosed) {
calendar.selectedDates = [dates[dateIndex]] calendar.selectedDates = [dates[dateIndex]]
} else { }
else {
calendar.selectedDates = [] calendar.selectedDates = []
} }
} else { }
else {
dates[dateIndex] = { dates[dateIndex] = {
...dates[dateIndex], ...dates[dateIndex],
choosed: !dates[dateIndex].choosed choosed: !dates[dateIndex].choosed,
} }
if (!calendar.selectedDates) { if (!calendar.selectedDates) {
calendar.selectedDates = [] calendar.selectedDates = []
} }
if (dates[dateIndex].choosed) { if (dates[dateIndex].choosed) {
calendar.selectedDates.push(dates[dateIndex]) calendar.selectedDates.push(dates[dateIndex])
} else { }
else {
calendar.selectedDates = calendar.selectedDates.filter( calendar.selectedDates = calendar.selectedDates.filter(
date => date =>
dateUtil.toTimeStr(date) !== dateUtil.toTimeStr(dates[dateIndex]) dateUtil.toTimeStr(date) !== dateUtil.toTimeStr(dates[dateIndex]),
) )
} }
} }
return { return {
calendarData: { calendarData: {
...calendar, ...calendar,
dates dates,
}, },
calendarConfig calendarConfig,
} }
}, },
onSwitchCalendar(date, calendarData = {}, component) { onSwitchCalendar(date, calendarData = {}, component) {
@ -108,21 +111,21 @@ export default () => {
} }
const updatedRenderData = calcJumpData({ const updatedRenderData = calcJumpData({
dateInfo: date, dateInfo: date,
config: calendarConfig config: calendarConfig,
}) })
return { return {
...calendarData, ...calendarData,
...updatedRenderData ...updatedRenderData,
} }
}, },
methods(component) { methods(component) {
return { return {
jump: dateInfo => { jump: (dateInfo) => {
if (Object.prototype.toString.call(dateInfo) !== '[object Object]') if (Object.prototype.toString.call(dateInfo) !== '[object Object]')
return return
const updatedRenderData = calcJumpData({ const updatedRenderData = calcJumpData({
dateInfo, dateInfo,
component component,
}) })
const existCalendarData = getCalendarData('calendar', component) const existCalendarData = getCalendarData('calendar', component)
const config = getCalendarConfig(component) const config = getCalendarConfig(component)
@ -130,13 +133,14 @@ export default () => {
const target = updatedRenderData.dates[dateInfo.date - 1] const target = updatedRenderData.dates[dateInfo.date - 1]
if (!updatedRenderData.selectedDates) { if (!updatedRenderData.selectedDates) {
updatedRenderData.selectedDates = [target] updatedRenderData.selectedDates = [target]
} else { }
else {
updatedRenderData.selectedDates.push(target) updatedRenderData.selectedDates.push(target)
} }
} }
return renderCalendar.call(component, { return renderCalendar.call(component, {
...existCalendarData, ...existCalendarData,
...updatedRenderData ...updatedRenderData,
}) })
}, },
getCalendarConfig() { getCalendarConfig() {
@ -148,7 +152,7 @@ export default () => {
reject('异常:未找到组件配置信息') reject('异常:未找到组件配置信息')
return return
} }
let conf = { ...component.config, ...config } const conf = { ...component.config, ...config }
component.config = conf component.config = conf
setCalendarData({ config: conf }, component) setCalendarData({ config: conf }, component)
.then(resolve) .then(resolve)
@ -164,66 +168,69 @@ export default () => {
if (config.chooseAreaMode) { if (config.chooseAreaMode) {
chooseAreaData = { chooseAreaData = {
chooseAreaTimestamp: [], chooseAreaTimestamp: [],
tempChooseAreaTimestamp: [] tempChooseAreaTimestamp: [],
} }
} }
if (!cancelDates.length) { if (!cancelDates.length) {
dates.forEach(item => { dates.forEach((item) => {
item.choosed = false item.choosed = false
}) })
updatedRenderData = { updatedRenderData = {
dates, dates,
selectedDates: [] selectedDates: [],
} }
} else { }
else {
const cancelDatesStr = cancelDates.map(date => const cancelDatesStr = cancelDates.map(date =>
dateUtil.toTimeStr(date) dateUtil.toTimeStr(date),
) )
const filterSelectedDates = selectedDates.filter( const filterSelectedDates = selectedDates.filter(
date => !cancelDatesStr.includes(dateUtil.toTimeStr(date)) date => !cancelDatesStr.includes(dateUtil.toTimeStr(date)),
) )
dates.forEach(date => { dates.forEach((date) => {
if (cancelDatesStr.includes(dateUtil.toTimeStr(date))) { if (cancelDatesStr.includes(dateUtil.toTimeStr(date))) {
date.choosed = false date.choosed = false
} }
}) })
updatedRenderData = { updatedRenderData = {
dates, dates,
selectedDates: filterSelectedDates selectedDates: filterSelectedDates,
} }
} }
return renderCalendar.call(component, { return renderCalendar.call(component, {
...existCalendarData, ...existCalendarData,
...updatedRenderData, ...updatedRenderData,
...chooseAreaData ...chooseAreaData,
}) })
}, },
setSelectedDates: targetDates => { setSelectedDates: (targetDates) => {
const existCalendarData = getCalendarData('calendar', component) const existCalendarData = getCalendarData('calendar', component)
let { dates, selectedDates = [] } = existCalendarData || {} const { dates, selectedDates = [] } = existCalendarData || {}
let __selectedDates = [] let __selectedDates = []
let __dates = dates let __dates = dates
if (!targetDates) { if (!targetDates) {
__dates = dates.map(item => { __dates = dates.map((item) => {
const date = { ...item } const date = { ...item }
date.choosed = true date.choosed = true
if (existCalendarData.showLabelAlways && date.showTodoLabel) { if (existCalendarData.showLabelAlways && date.showTodoLabel) {
date.showTodoLabel = true date.showTodoLabel = true
} else { }
else {
date.showTodoLabel = false date.showTodoLabel = false
} }
return date return date
}) })
__selectedDates = dates __selectedDates = dates
} else if (targetDates && targetDates.length) { }
else if (targetDates && targetDates.length) {
const allSelected = dateUtil.uniqueArrayByDate( const allSelected = dateUtil.uniqueArrayByDate(
selectedDates.concat(targetDates) selectedDates.concat(targetDates),
) )
const allSelectedDateStr = allSelected.map(d => const allSelectedDateStr = allSelected.map(d =>
dateUtil.toTimeStr(d) dateUtil.toTimeStr(d),
) )
__dates = dates.map(item => { __dates = dates.map((item) => {
const date = { ...item } const date = { ...item }
if (allSelectedDateStr.includes(dateUtil.toTimeStr(date))) { if (allSelectedDateStr.includes(dateUtil.toTimeStr(date))) {
date.choosed = true date.choosed = true
@ -231,7 +238,8 @@ export default () => {
} }
if (existCalendarData.showLabelAlways && date.showTodoLabel) { if (existCalendarData.showLabelAlways && date.showTodoLabel) {
date.showTodoLabel = true date.showTodoLabel = true
} else { }
else {
date.showTodoLabel = false date.showTodoLabel = false
} }
return date return date
@ -240,38 +248,40 @@ export default () => {
return renderCalendar.call(component, { return renderCalendar.call(component, {
...existCalendarData, ...existCalendarData,
dates: __dates, dates: __dates,
selectedDates: __selectedDates selectedDates: __selectedDates,
}) })
}, },
setDateStyle: toSetDates => { setDateStyle: (toSetDates) => {
if (!Array.isArray(toSetDates)) return Promise.reject() if (!Array.isArray(toSetDates))
return Promise.reject()
const existCalendarData = getCalendarData('calendar', component) const existCalendarData = getCalendarData('calendar', component)
const { dates = [], specialStyleDates } = existCalendarData || {} const { dates = [], specialStyleDates } = existCalendarData || {}
if (Array.isArray(specialStyleDates)) { if (Array.isArray(specialStyleDates)) {
toSetDates = dateUtil.uniqueArrayByDate([ toSetDates = dateUtil.uniqueArrayByDate([
...specialStyleDates, ...specialStyleDates,
...toSetDates ...toSetDates,
]) ])
} }
const toSetDatesStr = toSetDates.map(item => dateUtil.toTimeStr(item)) const toSetDatesStr = toSetDates.map(item => dateUtil.toTimeStr(item))
const _dates = dates.map(item => { const _dates = dates.map((item) => {
const idx = toSetDatesStr.indexOf(dateUtil.toTimeStr(item)) const idx = toSetDatesStr.indexOf(dateUtil.toTimeStr(item))
if (idx > -1) { if (idx > -1) {
return { return {
...item, ...item,
class: toSetDates[idx].class class: toSetDates[idx].class,
} }
} else { }
else {
return item return item
} }
}) })
return renderCalendar.call(component, { return renderCalendar.call(component, {
...existCalendarData, ...existCalendarData,
dates: _dates, dates: _dates,
specialStyleDates: toSetDates specialStyleDates: toSetDates,
}) })
} },
} }
} },
} }
} }

30
src/components/calendar/plugins/preset/get-calendar-data.js

@ -4,14 +4,14 @@
* @Date: 2020-10-08 21:22:09* * @Date: 2020-10-08 21:22:09*
* @Last Modified by: drfu * @Last Modified by: drfu
* @Last Modified time: 2020-10-11 13:42:37 * @Last Modified time: 2020-10-11 13:42:37
* */ */
import { getCalendarData, logger, getCalendarConfig } from '../../utils/index' import { getCalendarConfig, getCalendarData, logger } from '../../utils/index'
function wrapDateWithLunar(dates = [], convertFn) { function wrapDateWithLunar(dates = [], convertFn) {
const datesWithLunar = JSON.parse(JSON.stringify(dates)).map(date => ({ const datesWithLunar = JSON.parse(JSON.stringify(dates)).map(date => ({
...date, ...date,
lunar: convertFn(date) lunar: convertFn(date),
})) }))
return datesWithLunar return datesWithLunar
} }
@ -25,21 +25,23 @@ export default () => {
const { curYear, curMonth } = getCalendarData('calendar', component) const { curYear, curMonth } = getCalendarData('calendar', component)
return { return {
year: curYear, year: curYear,
month: curMonth month: curMonth,
} }
}, },
getSelectedDates: (options = {}) => { getSelectedDates: (options = {}) => {
const dates = const dates
getCalendarData('calendar.selectedDates', component) || [] = getCalendarData('calendar.selectedDates', component) || []
const config = getCalendarConfig(component) || {} const config = getCalendarConfig(component) || {}
if (options.lunar && !config.showLunar) { if (options.lunar && !config.showLunar) {
const injectedFns = component.calendar || {} const injectedFns = component.calendar || {}
if (typeof injectedFns.convertSolarLunar === 'function') { if (typeof injectedFns.convertSolarLunar === 'function') {
return wrapDateWithLunar(dates, injectedFns.convertSolarLunar) return wrapDateWithLunar(dates, injectedFns.convertSolarLunar)
} else { }
else {
logger.warn('获取农历信息需引入农历插件') logger.warn('获取农历信息需引入农历插件')
} }
} else { }
else {
return dates return dates
} }
}, },
@ -50,20 +52,22 @@ export default () => {
const injectedFns = component.calendar || {} const injectedFns = component.calendar || {}
if (typeof injectedFns.convertSolarLunar === 'function') { if (typeof injectedFns.convertSolarLunar === 'function') {
return wrapDateWithLunar(dates, injectedFns.convertSolarLunar) return wrapDateWithLunar(dates, injectedFns.convertSolarLunar)
} else { }
else {
logger.warn('获取农历信息需引入农历插件') logger.warn('获取农历信息需引入农历插件')
} }
} else { }
else {
return dates return dates
} }
}, },
getCalendarAllData: () => { getCalendarAllData: () => {
return { return {
data: getCalendarData('calendar', component) || {}, data: getCalendarData('calendar', component) || {},
config: getCalendarConfig(component) || {} config: getCalendarConfig(component) || {},
} }
} },
} }
} },
} }
} }

2
src/components/calendar/plugins/preset/index.d.ts vendored

@ -1 +1 @@
export {}; export {}

2
src/components/calendar/plugins/preset/index.js

@ -3,7 +3,7 @@ import getCalendarData from './get-calendar-data'
const preset = [ const preset = [
['base', base()], ['base', base()],
['get-calendar-data', getCalendarData()] ['get-calendar-data', getCalendarData()],
] ]
export default preset export default preset

2
src/components/calendar/plugins/selectable.d.ts vendored

@ -1 +1 @@
export {}; export {}

104
src/components/calendar/plugins/selectable.js

@ -4,10 +4,10 @@
* @Date: 2020-10-08 21:22:09* * @Date: 2020-10-08 21:22:09*
* @Last Modified by: drfu * @Last Modified by: drfu
* @Last Modified time: 2020-10-08 21:25:00 * @Last Modified time: 2020-10-08 21:25:00
* */ */
import { getCalendarData, dateUtil, logger } from '../utils/index'
import { renderCalendar } from '../render' import { renderCalendar } from '../render'
import { dateUtil, getCalendarData, logger } from '../utils/index'
function convertEnableAreaToTimestamp(timearea = []) { function convertEnableAreaToTimestamp(timearea = []) {
const start = timearea[0].split('-') const start = timearea[0].split('-')
@ -24,7 +24,7 @@ function convertEnableAreaToTimestamp(timearea = []) {
start, start,
end, end,
startTimestamp, startTimestamp,
endTimestamp endTimestamp,
} }
} }
@ -33,39 +33,46 @@ function isValiditeOfDateArea(dateArea) {
start, start,
end, end,
startTimestamp, startTimestamp,
endTimestamp endTimestamp,
} = convertEnableAreaToTimestamp(dateArea) } = convertEnableAreaToTimestamp(dateArea)
if (!start || !end) return if (!start || !end)
return
const datesCountOfStart = dateUtil.getDatesCountOfMonth(start[0], start[1]) const datesCountOfStart = dateUtil.getDatesCountOfMonth(start[0], start[1])
const datesCountOfEnd = dateUtil.getDatesCountOfMonth(end[0], end[1]) const datesCountOfEnd = dateUtil.getDatesCountOfMonth(end[0], end[1])
if (start[2] > datesCountOfStart || start[2] < 1) { if (start[2] > datesCountOfStart || start[2] < 1) {
logger.warn('enableArea() 开始日期错误,指定日期不在指定月份天数范围内') logger.warn('enableArea() 开始日期错误,指定日期不在指定月份天数范围内')
return false return false
} else if (start[1] > 12 || start[1] < 1) { }
else if (start[1] > 12 || start[1] < 1) {
logger.warn('enableArea() 开始日期错误,月份超出1-12月份') logger.warn('enableArea() 开始日期错误,月份超出1-12月份')
return false return false
} else if (end[2] > datesCountOfEnd || end[2] < 1) { }
else if (end[2] > datesCountOfEnd || end[2] < 1) {
logger.warn('enableArea() 截止日期错误,指定日期不在指定月份天数范围内') logger.warn('enableArea() 截止日期错误,指定日期不在指定月份天数范围内')
return false return false
} else if (end[1] > 12 || end[1] < 1) { }
else if (end[1] > 12 || end[1] < 1) {
logger.warn('enableArea() 截止日期错误,月份超出1-12月份') logger.warn('enableArea() 截止日期错误,月份超出1-12月份')
return false return false
} else if (startTimestamp > endTimestamp) { }
else if (startTimestamp > endTimestamp) {
logger.warn('enableArea()参数最小日期大于了最大日期') logger.warn('enableArea()参数最小日期大于了最大日期')
return false return false
} else { }
else {
return true return true
} }
} }
function handleDisableMode(calendarConfig) { function handleDisableMode(calendarConfig) {
const { disableMode } = calendarConfig const { disableMode } = calendarConfig
if (!disableMode) return {} if (!disableMode)
const disableBound = return {}
dateUtil.getTimeStamp(disableMode.date) || dateUtil.todayTimestamp() const disableBound
= dateUtil.getTimeStamp(disableMode.date) || dateUtil.todayTimestamp()
return { return {
disableBound, disableBound,
disableType: disableMode.type disableType: disableMode.type,
} }
} }
@ -73,11 +80,12 @@ function disabledByConfig(dateInfo, currentDate, calendarConfig) {
const date = { ...dateInfo } const date = { ...dateInfo }
const { disableType, disableBound } = handleDisableMode(calendarConfig) const { disableType, disableBound } = handleDisableMode(calendarConfig)
if ( if (
(disableType === 'before' && disableBound && currentDate < disableBound) || (disableType === 'before' && disableBound && currentDate < disableBound)
(disableType === 'after' && disableBound && currentDate > disableBound) || (disableType === 'after' && disableBound && currentDate > disableBound)
) { ) {
date.disable = true date.disable = true
} else { }
else {
date.disable = false date.disable = false
} }
return date return date
@ -92,34 +100,38 @@ export default () => {
enableArea, enableArea,
enableDates, enableDates,
disableDates, disableDates,
renderCausedBy renderCausedBy,
} = calendarData } = calendarData
const _dates = [...dates].map(date => { const _dates = [...dates].map((date) => {
let item = { ...date } const item = { ...date }
const timeStr = dateUtil.toTimeStr(date) const timeStr = dateUtil.toTimeStr(date)
const timestamp = +dateUtil.getTimeStamp(item) const timestamp = +dateUtil.getTimeStamp(item)
if (renderCausedBy === 'enableDates') { if (renderCausedBy === 'enableDates') {
if (enableDates && enableDates.length) { if (enableDates && enableDates.length) {
if (enableDates.includes(timeStr)) { if (enableDates.includes(timeStr)) {
item.disable = false item.disable = false
} else { }
else {
item.disable = true item.disable = true
} }
return item return item
} }
} else if (renderCausedBy === 'enableArea') { }
else if (renderCausedBy === 'enableArea') {
if (enableArea && enableArea.length) { if (enableArea && enableArea.length) {
const [startTimestamp, endTimestamp] = enableArea || [] const [startTimestamp, endTimestamp] = enableArea || []
const ifOutofArea = const ifOutofArea
+startTimestamp > timestamp || timestamp > +endTimestamp = +startTimestamp > timestamp || timestamp > +endTimestamp
item.disable = ifOutofArea item.disable = ifOutofArea
return item return item
} }
} else if (renderCausedBy === 'disableDates') { }
else if (renderCausedBy === 'disableDates') {
if (disableDates && disableDates.length) { if (disableDates && disableDates.length) {
if (disableDates && disableDates.includes(timeStr)) { if (disableDates && disableDates.includes(timeStr)) {
item.disable = true item.disable = true
} else { }
else {
item.disable = false item.disable = false
} }
return item return item
@ -131,9 +143,9 @@ export default () => {
return { return {
calendarData: { calendarData: {
...calendarData, ...calendarData,
dates: _dates dates: _dates,
}, },
calendarConfig calendarConfig,
} }
}, },
methods(component) { methods(component) {
@ -145,26 +157,28 @@ export default () => {
const existCalendarData = getCalendarData('calendar', component) const existCalendarData = getCalendarData('calendar', component)
const { const {
startTimestamp, startTimestamp,
endTimestamp endTimestamp,
} = convertEnableAreaToTimestamp(dateArea) } = convertEnableAreaToTimestamp(dateArea)
return renderCalendar.call(component, { return renderCalendar.call(component, {
...existCalendarData, ...existCalendarData,
renderCausedBy: 'enableArea', renderCausedBy: 'enableArea',
enableArea: [startTimestamp, endTimestamp] enableArea: [startTimestamp, endTimestamp],
}) })
} }
} else { }
else {
return Promise.inject( return Promise.inject(
'enableArea()参数需为时间范围数组,形如:["2018-8-4" , "2018-8-24"]' 'enableArea()参数需为时间范围数组,形如:["2018-8-4" , "2018-8-24"]',
) )
} }
}, },
enableDates: (toSet = []) => { enableDates: (toSet = []) => {
if (!toSet.length) return if (!toSet.length)
return
const existCalendarData = getCalendarData('calendar', component) const existCalendarData = getCalendarData('calendar', component)
const { enableDates = [] } = existCalendarData || {} const { enableDates = [] } = existCalendarData || {}
let toSetDates = toSet.map(item => { let toSetDates = toSet.map((item) => {
if (typeof item === 'string') { if (typeof item === 'string') {
return dateUtil.transformDateRow2Dict(item) return dateUtil.transformDateRow2Dict(item)
} }
@ -173,25 +187,25 @@ export default () => {
if (enableDates.length) { if (enableDates.length) {
toSetDates = dateUtil.uniqueArrayByDate([ toSetDates = dateUtil.uniqueArrayByDate([
...toSetDates, ...toSetDates,
...enableDates.map(d => dateUtil.transformDateRow2Dict(d)) ...enableDates.map(d => dateUtil.transformDateRow2Dict(d)),
]) ])
} }
return renderCalendar.call(component, { return renderCalendar.call(component, {
...existCalendarData, ...existCalendarData,
renderCausedBy: 'enableDates', renderCausedBy: 'enableDates',
enableDates: toSetDates.map(date => { enableDates: toSetDates.map((date) => {
if (typeof date !== 'string') { if (typeof date !== 'string') {
return dateUtil.toTimeStr(date) return dateUtil.toTimeStr(date)
} }
return date return date
}) }),
}) })
}, },
disableDates: toSet => { disableDates: (toSet) => {
const existCalendarData = getCalendarData('calendar', component) const existCalendarData = getCalendarData('calendar', component)
const { disableDates = [], dates = [] } = existCalendarData || {} const { disableDates = [], dates = [] } = existCalendarData || {}
let toSetDates = toSet.map(item => { let toSetDates = toSet.map((item) => {
let date = { ...item } const date = { ...item }
if (typeof date === 'string') { if (typeof date === 'string') {
return dateUtil.transformDateRow2Dict(item) return dateUtil.transformDateRow2Dict(item)
} }
@ -200,22 +214,22 @@ export default () => {
if (disableDates && disableDates.length) { if (disableDates && disableDates.length) {
toSetDates = dateUtil.uniqueArrayByDate([ toSetDates = dateUtil.uniqueArrayByDate([
...toSetDates, ...toSetDates,
...disableDates.map(d => dateUtil.transformDateRow2Dict(d)) ...disableDates.map(d => dateUtil.transformDateRow2Dict(d)),
]) ])
} }
return renderCalendar.call(component, { return renderCalendar.call(component, {
...existCalendarData, ...existCalendarData,
renderCausedBy: 'disableDates', renderCausedBy: 'disableDates',
dates, dates,
disableDates: toSetDates.map(date => { disableDates: toSetDates.map((date) => {
if (typeof date !== 'string') { if (typeof date !== 'string') {
return dateUtil.toTimeStr(date) return dateUtil.toTimeStr(date)
} }
return date return date
}) }),
}) })
} },
} }
} },
} }
} }

662
src/components/calendar/plugins/solarLunar/convertSolarLunar.js

@ -6,7 +6,7 @@
*/ */
/* 公历年月日转农历数据 返回json */ /* 公历年月日转农历数据 返回json */
// calendar.solar2lunar(1987,11,01); // calendar.solar2lunar(1987,11,01);
/** 农历年月日转公历年月日 **/ /** 农历年月日转公历年月日 */
// calendar.lunar2solar(1987,9,10); // calendar.lunar2solar(1987,9,10);
// 调用以上方法后返回类似如下object(json)具体以上就不需要解释了吧! // 调用以上方法后返回类似如下object(json)具体以上就不需要解释了吧!
// c开头的是公历各属性值 l开头的自然就是农历咯 gz开头的就是天干地支纪年的数据啦~ // c开头的是公历各属性值 l开头的自然就是农历咯 gz开头的就是天干地支纪年的数据啦~
@ -39,208 +39,208 @@ const calendar = {
* @return Hex * @return Hex
*/ */
lunarInfo: [ lunarInfo: [
0x04bd8, 0x04BD8,
0x04ae0, 0x04AE0,
0x0a570, 0x0A570,
0x054d5, 0x054D5,
0x0d260, 0x0D260,
0x0d950, 0x0D950,
0x16554, 0x16554,
0x056a0, 0x056A0,
0x09ad0, 0x09AD0,
0x055d2, // 1900-1909 0x055D2, // 1900-1909
0x04ae0, 0x04AE0,
0x0a5b6, 0x0A5B6,
0x0a4d0, 0x0A4D0,
0x0d250, 0x0D250,
0x1d255, 0x1D255,
0x0b540, 0x0B540,
0x0d6a0, 0x0D6A0,
0x0ada2, 0x0ADA2,
0x095b0, 0x095B0,
0x14977, // 1910-1919 0x14977, // 1910-1919
0x04970, 0x04970,
0x0a4b0, 0x0A4B0,
0x0b4b5, 0x0B4B5,
0x06a50, 0x06A50,
0x06d40, 0x06D40,
0x1ab54, 0x1AB54,
0x02b60, 0x02B60,
0x09570, 0x09570,
0x052f2, 0x052F2,
0x04970, // 1920-1929 0x04970, // 1920-1929
0x06566, 0x06566,
0x0d4a0, 0x0D4A0,
0x0ea50, 0x0EA50,
0x06e95, 0x06E95,
0x05ad0, 0x05AD0,
0x02b60, 0x02B60,
0x186e3, 0x186E3,
0x092e0, 0x092E0,
0x1c8d7, 0x1C8D7,
0x0c950, // 1930-1939 0x0C950, // 1930-1939
0x0d4a0, 0x0D4A0,
0x1d8a6, 0x1D8A6,
0x0b550, 0x0B550,
0x056a0, 0x056A0,
0x1a5b4, 0x1A5B4,
0x025d0, 0x025D0,
0x092d0, 0x092D0,
0x0d2b2, 0x0D2B2,
0x0a950, 0x0A950,
0x0b557, // 1940-1949 0x0B557, // 1940-1949
0x06ca0, 0x06CA0,
0x0b550, 0x0B550,
0x15355, 0x15355,
0x04da0, 0x04DA0,
0x0a5b0, 0x0A5B0,
0x14573, 0x14573,
0x052b0, 0x052B0,
0x0a9a8, 0x0A9A8,
0x0e950, 0x0E950,
0x06aa0, // 1950-1959 0x06AA0, // 1950-1959
0x0aea6, 0x0AEA6,
0x0ab50, 0x0AB50,
0x04b60, 0x04B60,
0x0aae4, 0x0AAE4,
0x0a570, 0x0A570,
0x05260, 0x05260,
0x0f263, 0x0F263,
0x0d950, 0x0D950,
0x05b57, 0x05B57,
0x056a0, // 1960-1969 0x056A0, // 1960-1969
0x096d0, 0x096D0,
0x04dd5, 0x04DD5,
0x04ad0, 0x04AD0,
0x0a4d0, 0x0A4D0,
0x0d4d4, 0x0D4D4,
0x0d250, 0x0D250,
0x0d558, 0x0D558,
0x0b540, 0x0B540,
0x0b6a0, 0x0B6A0,
0x195a6, // 1970-1979 0x195A6, // 1970-1979
0x095b0, 0x095B0,
0x049b0, 0x049B0,
0x0a974, 0x0A974,
0x0a4b0, 0x0A4B0,
0x0b27a, 0x0B27A,
0x06a50, 0x06A50,
0x06d40, 0x06D40,
0x0af46, 0x0AF46,
0x0ab60, 0x0AB60,
0x09570, // 1980-1989 0x09570, // 1980-1989
0x04af5, 0x04AF5,
0x04970, 0x04970,
0x064b0, 0x064B0,
0x074a3, 0x074A3,
0x0ea50, 0x0EA50,
0x06b58, 0x06B58,
0x055c0, 0x055C0,
0x0ab60, 0x0AB60,
0x096d5, 0x096D5,
0x092e0, // 1990-1999 0x092E0, // 1990-1999
0x0c960, 0x0C960,
0x0d954, 0x0D954,
0x0d4a0, 0x0D4A0,
0x0da50, 0x0DA50,
0x07552, 0x07552,
0x056a0, 0x056A0,
0x0abb7, 0x0ABB7,
0x025d0, 0x025D0,
0x092d0, 0x092D0,
0x0cab5, // 2000-2009 0x0CAB5, // 2000-2009
0x0a950, 0x0A950,
0x0b4a0, 0x0B4A0,
0x0baa4, 0x0BAA4,
0x0ad50, 0x0AD50,
0x055d9, 0x055D9,
0x04ba0, 0x04BA0,
0x0a5b0, 0x0A5B0,
0x15176, 0x15176,
0x052b0, 0x052B0,
0x0a930, // 2010-2019 0x0A930, // 2010-2019
0x07954, 0x07954,
0x06aa0, 0x06AA0,
0x0ad50, 0x0AD50,
0x05b52, 0x05B52,
0x04b60, 0x04B60,
0x0a6e6, 0x0A6E6,
0x0a4e0, 0x0A4E0,
0x0d260, 0x0D260,
0x0ea65, 0x0EA65,
0x0d530, // 2020-2029 0x0D530, // 2020-2029
0x05aa0, 0x05AA0,
0x076a3, 0x076A3,
0x096d0, 0x096D0,
0x04afb, 0x04AFB,
0x04ad0, 0x04AD0,
0x0a4d0, 0x0A4D0,
0x1d0b6, 0x1D0B6,
0x0d250, 0x0D250,
0x0d520, 0x0D520,
0x0dd45, // 2030-2039 0x0DD45, // 2030-2039
0x0b5a0, 0x0B5A0,
0x056d0, 0x056D0,
0x055b2, 0x055B2,
0x049b0, 0x049B0,
0x0a577, 0x0A577,
0x0a4b0, 0x0A4B0,
0x0aa50, 0x0AA50,
0x1b255, 0x1B255,
0x06d20, 0x06D20,
0x0ada0, // 2040-2049 0x0ADA0, // 2040-2049
/** Add By JJonline@JJonline.Cn **/ /** Add By JJonline@JJonline.Cn */
0x14b63, 0x14B63,
0x09370, 0x09370,
0x049f8, 0x049F8,
0x04970, 0x04970,
0x064b0, 0x064B0,
0x168a6, 0x168A6,
0x0ea50, 0x0EA50,
0x06b20, 0x06B20,
0x1a6c4, 0x1A6C4,
0x0aae0, // 2050-2059 0x0AAE0, // 2050-2059
0x0a2e0, 0x0A2E0,
0x0d2e3, 0x0D2E3,
0x0c960, 0x0C960,
0x0d557, 0x0D557,
0x0d4a0, 0x0D4A0,
0x0da50, 0x0DA50,
0x05d55, 0x05D55,
0x056a0, 0x056A0,
0x0a6d0, 0x0A6D0,
0x055d4, // 2060-2069 0x055D4, // 2060-2069
0x052d0, 0x052D0,
0x0a9b8, 0x0A9B8,
0x0a950, 0x0A950,
0x0b4a0, 0x0B4A0,
0x0b6a6, 0x0B6A6,
0x0ad50, 0x0AD50,
0x055a0, 0x055A0,
0x0aba4, 0x0ABA4,
0x0a5b0, 0x0A5B0,
0x052b0, // 2070-2079 0x052B0, // 2070-2079
0x0b273, 0x0B273,
0x06930, 0x06930,
0x07337, 0x07337,
0x06aa0, 0x06AA0,
0x0ad50, 0x0AD50,
0x14b55, 0x14B55,
0x04b60, 0x04B60,
0x0a570, 0x0A570,
0x054e4, 0x054E4,
0x0d160, // 2080-2089 0x0D160, // 2080-2089
0x0e968, 0x0E968,
0x0d520, 0x0D520,
0x0daa0, 0x0DAA0,
0x16aa6, 0x16AA6,
0x056d0, 0x056D0,
0x04ae0, 0x04AE0,
0x0a9d4, 0x0A9D4,
0x0a2d0, 0x0A2D0,
0x0d150, 0x0D150,
0x0f252, // 2090-2099 0x0F252, // 2090-2099
0x0d520 0x0D520,
], // 2100 ], // 2100
/** /**
@ -257,15 +257,15 @@ const calendar = {
*/ */
Gan: [ Gan: [
'\u7532', '\u7532',
'\u4e59', '\u4E59',
'\u4e19', '\u4E19',
'\u4e01', '\u4E01',
'\u620a', '\u620A',
'\u5df1', '\u5DF1',
'\u5e9a', '\u5E9A',
'\u8f9b', '\u8F9B',
'\u58ec', '\u58EC',
'\u7678' '\u7678',
], ],
/** /**
@ -275,18 +275,18 @@ const calendar = {
* @return Cn string * @return Cn string
*/ */
Zhi: [ Zhi: [
'\u5b50', '\u5B50',
'\u4e11', '\u4E11',
'\u5bc5', '\u5BC5',
'\u536f', '\u536F',
'\u8fb0', '\u8FB0',
'\u5df3', '\u5DF3',
'\u5348', '\u5348',
'\u672a', '\u672A',
'\u7533', '\u7533',
'\u9149', '\u9149',
'\u620c', '\u620C',
'\u4ea5' '\u4EA5',
], ],
/** /**
@ -296,18 +296,18 @@ const calendar = {
* @return Cn string * @return Cn string
*/ */
Animals: [ Animals: [
'\u9f20', '\u9F20',
'\u725b', '\u725B',
'\u864e', '\u864E',
'\u5154', '\u5154',
'\u9f99', '\u9F99',
'\u86c7', '\u86C7',
'\u9a6c', '\u9A6C',
'\u7f8a', '\u7F8A',
'\u7334', '\u7334',
'\u9e21', '\u9E21',
'\u72d7', '\u72D7',
'\u732a' '\u732A',
], ],
/** /**
@ -317,30 +317,30 @@ const calendar = {
* @return Cn string * @return Cn string
*/ */
solarTerm: [ solarTerm: [
'\u5c0f\u5bd2', '\u5C0F\u5BD2',
'\u5927\u5bd2', '\u5927\u5BD2',
'\u7acb\u6625', '\u7ACB\u6625',
'\u96e8\u6c34', '\u96E8\u6C34',
'\u60ca\u86f0', '\u60CA\u86F0',
'\u6625\u5206', '\u6625\u5206',
'\u6e05\u660e', '\u6E05\u660E',
'\u8c37\u96e8', '\u8C37\u96E8',
'\u7acb\u590f', '\u7ACB\u590F',
'\u5c0f\u6ee1', '\u5C0F\u6EE1',
'\u8292\u79cd', '\u8292\u79CD',
'\u590f\u81f3', '\u590F\u81F3',
'\u5c0f\u6691', '\u5C0F\u6691',
'\u5927\u6691', '\u5927\u6691',
'\u7acb\u79cb', '\u7ACB\u79CB',
'\u5904\u6691', '\u5904\u6691',
'\u767d\u9732', '\u767D\u9732',
'\u79cb\u5206', '\u79CB\u5206',
'\u5bd2\u9732', '\u5BD2\u9732',
'\u971c\u964d', '\u971C\u964D',
'\u7acb\u51ac', '\u7ACB\u51AC',
'\u5c0f\u96ea', '\u5C0F\u96EA',
'\u5927\u96ea', '\u5927\u96EA',
'\u51ac\u81f3' '\u51AC\u81F3',
], ],
/** /**
@ -549,7 +549,7 @@ const calendar = {
'665f67f0e37f1489801eb072297c35', '665f67f0e37f1489801eb072297c35',
'7ec967f0e37f14998082b0787b06bd', '7ec967f0e37f14998082b0787b06bd',
'7f07e7f0e47f531b0723b0b6fb0721', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f531b0b0bb0b6fb0722' '7f0e27f1487f531b0b0bb0b6fb0722',
], ],
/** /**
@ -559,17 +559,17 @@ const calendar = {
* @return Cn string * @return Cn string
*/ */
nStr1: [ nStr1: [
'\u65e5', '\u65E5',
'\u4e00', '\u4E00',
'\u4e8c', '\u4E8C',
'\u4e09', '\u4E09',
'\u56db', '\u56DB',
'\u4e94', '\u4E94',
'\u516d', '\u516D',
'\u4e03', '\u4E03',
'\u516b', '\u516B',
'\u4e5d', '\u4E5D',
'\u5341' '\u5341',
], ],
/** /**
@ -578,7 +578,7 @@ const calendar = {
* @trans ['初','十','廿','卅'] * @trans ['初','十','廿','卅']
* @return Cn string * @return Cn string
*/ */
nStr2: ['\u521d', '\u5341', '\u5eff', '\u5345'], nStr2: ['\u521D', '\u5341', '\u5EFF', '\u5345'],
/** /**
* 月份转农历称呼速查表 * 月份转农历称呼速查表
@ -587,18 +587,18 @@ const calendar = {
* @return Cn string * @return Cn string
*/ */
nStr3: [ nStr3: [
'\u6b63', '\u6B63',
'\u4e8c', '\u4E8C',
'\u4e09', '\u4E09',
'\u56db', '\u56DB',
'\u4e94', '\u4E94',
'\u516d', '\u516D',
'\u4e03', '\u4E03',
'\u516b', '\u516B',
'\u4e5d', '\u4E5D',
'\u5341', '\u5341',
'\u51ac', '\u51AC',
'\u814a' '\u814A',
], ],
/** /**
@ -607,7 +607,7 @@ const calendar = {
* @return Number * @return Number
* @eg:var count = calendar.lYearDays(1987) ;//count=387 * @eg:var count = calendar.lYearDays(1987) ;//count=387
*/ */
lYearDays: function(y) { lYearDays(y) {
let i let i
let sum = 348 let sum = 348
for (i = 0x8000; i > 0x8; i >>= 1) { for (i = 0x8000; i > 0x8; i >>= 1) {
@ -622,9 +622,9 @@ const calendar = {
* @return Number (0-12) * @return Number (0-12)
* @eg:var leapMonth = calendar.leapMonth(1987) ;//leapMonth=6 * @eg:var leapMonth = calendar.leapMonth(1987) ;//leapMonth=6
*/ */
leapMonth: function(y) { leapMonth(y) {
// 闰字编码 \u95f0 // 闰字编码 \u95f0
return calendar.lunarInfo[y - 1900] & 0xf return calendar.lunarInfo[y - 1900] & 0xF
}, },
/** /**
@ -633,7 +633,7 @@ const calendar = {
* @return Number (02930) * @return Number (02930)
* @eg:var leapMonthDay = calendar.leapDays(1987) ;//leapMonthDay=29 * @eg:var leapMonthDay = calendar.leapDays(1987) ;//leapMonthDay=29
*/ */
leapDays: function(y) { leapDays(y) {
if (calendar.leapMonth(y)) { if (calendar.leapMonth(y)) {
return calendar.lunarInfo[y - 1900] & 0x10000 ? 30 : 29 return calendar.lunarInfo[y - 1900] & 0x10000 ? 30 : 29
} }
@ -646,8 +646,9 @@ const calendar = {
* @return Number (-12930) * @return Number (-12930)
* @eg:var MonthDay = calendar.monthDays(1987,9) ;//MonthDay=29 * @eg:var MonthDay = calendar.monthDays(1987,9) ;//MonthDay=29
*/ */
monthDays: function(y, m) { monthDays(y, m) {
if (m > 12 || m < 1) return -1 // 月份参数从1至12,参数错误返回-1 if (m > 12 || m < 1)
return -1 // 月份参数从1至12,参数错误返回-1
return calendar.lunarInfo[y - 1900] & (0x10000 >> m) ? 30 : 29 return calendar.lunarInfo[y - 1900] & (0x10000 >> m) ? 30 : 29
}, },
@ -657,13 +658,15 @@ const calendar = {
* @return Number (-128293031) * @return Number (-128293031)
* @eg:var solarMonthDay = calendar.leapDays(1987) ;//solarMonthDay=30 * @eg:var solarMonthDay = calendar.leapDays(1987) ;//solarMonthDay=30
*/ */
solarDays: function(y, m) { solarDays(y, m) {
if (m > 12 || m < 1) return -1 // 若参数错误 返回-1 if (m > 12 || m < 1)
return -1 // 若参数错误 返回-1
const ms = m - 1 const ms = m - 1
if (+ms === 1) { if (+ms === 1) {
// 2月份的闰平规律测算后确认返回28或29 // 2月份的闰平规律测算后确认返回28或29
return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0 ? 29 : 28 return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0 ? 29 : 28
} else { }
else {
return calendar.solarMonth[ms] return calendar.solarMonth[ms]
} }
}, },
@ -673,11 +676,13 @@ const calendar = {
* @param lYear 农历年的年份数 * @param lYear 农历年的年份数
* @return Cn string * @return Cn string
*/ */
toGanZhiYear: function(lYear) { toGanZhiYear(lYear) {
let ganKey = (lYear - 3) % 10 let ganKey = (lYear - 3) % 10
let zhiKey = (lYear - 3) % 12 let zhiKey = (lYear - 3) % 12
if (+ganKey === 0) ganKey = 10 // 如果余数为0则为最后一个天干 if (+ganKey === 0)
if (+zhiKey === 0) zhiKey = 12 // 如果余数为0则为最后一个地支 ganKey = 10 // 如果余数为0则为最后一个天干
if (+zhiKey === 0)
zhiKey = 12 // 如果余数为0则为最后一个地支
return calendar.Gan[ganKey - 1] + calendar.Zhi[zhiKey - 1] return calendar.Gan[ganKey - 1] + calendar.Zhi[zhiKey - 1]
}, },
@ -687,11 +692,11 @@ const calendar = {
* @param cDay [description] * @param cDay [description]
* @return Cn string * @return Cn string
*/ */
toAstro: function(cMonth, cDay) { toAstro(cMonth, cDay) {
const s = const s
'\u9b54\u7faf\u6c34\u74f6\u53cc\u9c7c\u767d\u7f8a\u91d1\u725b\u53cc\u5b50\u5de8\u87f9\u72ee\u5b50\u5904\u5973\u5929\u79e4\u5929\u874e\u5c04\u624b\u9b54\u7faf' = '\u9B54\u7FAF\u6C34\u74F6\u53CC\u9C7C\u767D\u7F8A\u91D1\u725B\u53CC\u5B50\u5DE8\u87F9\u72EE\u5B50\u5904\u5973\u5929\u79E4\u5929\u874E\u5C04\u624B\u9B54\u7FAF'
const arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22] const arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22]
return s.substr(cMonth * 2 - (cDay < arr[cMonth - 1] ? 2 : 0), 2) + '\u5ea7' // 座 return `${s.substr(cMonth * 2 - (cDay < arr[cMonth - 1] ? 2 : 0), 2)}\u5EA7` // 座
}, },
/** /**
@ -699,7 +704,7 @@ const calendar = {
* @param offset 相对甲子的偏移量 * @param offset 相对甲子的偏移量
* @return Cn string * @return Cn string
*/ */
toGanZhi: function(offset) { toGanZhi(offset) {
return calendar.Gan[offset % 10] + calendar.Zhi[offset % 12] return calendar.Gan[offset % 10] + calendar.Zhi[offset % 12]
}, },
@ -709,17 +714,19 @@ const calendar = {
* @return day Number * @return day Number
* @eg:var _24 = calendar.getTerm(1987,3) ;//_24=4;意即1987年2月4日立春 * @eg:var _24 = calendar.getTerm(1987,3) ;//_24=4;意即1987年2月4日立春
*/ */
getTerm: function(y, n) { getTerm(y, n) {
if (y < 1900 || y > 2100) return -1 if (y < 1900 || y > 2100)
if (n < 1 || n > 24) return -1 return -1
if (n < 1 || n > 24)
return -1
const _table = calendar.sTermInfo[y - 1900] const _table = calendar.sTermInfo[y - 1900]
const _info = [ const _info = [
parseInt('0x' + _table.substr(0, 5)).toString(), Number.parseInt(`0x${_table.substr(0, 5)}`).toString(),
parseInt('0x' + _table.substr(5, 5)).toString(), Number.parseInt(`0x${_table.substr(5, 5)}`).toString(),
parseInt('0x' + _table.substr(10, 5)).toString(), Number.parseInt(`0x${_table.substr(10, 5)}`).toString(),
parseInt('0x' + _table.substr(15, 5)).toString(), Number.parseInt(`0x${_table.substr(15, 5)}`).toString(),
parseInt('0x' + _table.substr(20, 5)).toString(), Number.parseInt(`0x${_table.substr(20, 5)}`).toString(),
parseInt('0x' + _table.substr(25, 5)).toString() Number.parseInt(`0x${_table.substr(25, 5)}`).toString(),
] ]
const _calday = [ const _calday = [
_info[0].substr(0, 1), _info[0].substr(0, 1),
@ -750,9 +757,9 @@ const calendar = {
_info[5].substr(0, 1), _info[5].substr(0, 1),
_info[5].substr(1, 2), _info[5].substr(1, 2),
_info[5].substr(3, 1), _info[5].substr(3, 1),
_info[5].substr(4, 2) _info[5].substr(4, 2),
] ]
return parseInt(_calday[n - 1]) return Number.parseInt(_calday[n - 1])
}, },
/** /**
@ -761,9 +768,10 @@ const calendar = {
* @return Cn string * @return Cn string
* @eg:var cnMonth = calendar.toChinaMonth(12) ;//cnMonth='腊月' * @eg:var cnMonth = calendar.toChinaMonth(12) ;//cnMonth='腊月'
*/ */
toChinaMonth: function(m) { toChinaMonth(m) {
// 月 => \u6708 // 月 => \u6708
if (m > 12 || m < 1) return -1 // 若参数错误 返回-1 if (m > 12 || m < 1)
return -1 // 若参数错误 返回-1
let s = calendar.nStr3[m - 1] let s = calendar.nStr3[m - 1]
s += '\u6708' // 加上月字 s += '\u6708' // 加上月字
return s return s
@ -775,18 +783,18 @@ const calendar = {
* @return Cn string * @return Cn string
* @eg:var cnDay = calendar.toChinaDay(21) ;//cnMonth='廿一' * @eg:var cnDay = calendar.toChinaDay(21) ;//cnMonth='廿一'
*/ */
toChinaDay: function(d) { toChinaDay(d) {
// 日 => \u65e5 // 日 => \u65e5
let s let s
switch (d) { switch (d) {
case 10: case 10:
s = '\u521d\u5341' s = '\u521D\u5341'
break break
case 20: case 20:
s = '\u4e8c\u5341' s = '\u4E8C\u5341'
break break
case 30: case 30:
s = '\u4e09\u5341' s = '\u4E09\u5341'
break break
default: default:
s = calendar.nStr2[Math.floor(d / 10)] s = calendar.nStr2[Math.floor(d / 10)]
@ -801,7 +809,7 @@ const calendar = {
* @return Cn string * @return Cn string
* @eg:var animal = calendar.getAnimal(1987) ;//animal='兔' * @eg:var animal = calendar.getAnimal(1987) ;//animal='兔'
*/ */
getAnimal: function(y) { getAnimal(y) {
return calendar.Animals[(y - 4) % 12] return calendar.Animals[(y - 4) % 12]
}, },
@ -813,7 +821,7 @@ const calendar = {
* @return JSON object * @return JSON object
* @eg:console.log(calendar.solar2lunar(1987,11,01)); * @eg:console.log(calendar.solar2lunar(1987,11,01));
*/ */
solar2lunar: function(y, m, d) { solar2lunar(y, m, d) {
// 参数区间1900.1.31~2100.12.31 // 参数区间1900.1.31~2100.12.31
// 年份限定、上限 // 年份限定、上限
if (y < 1900 || y > 2100) { if (y < 1900 || y > 2100) {
@ -827,8 +835,9 @@ const calendar = {
let objDate let objDate
if (!y) { if (!y) {
objDate = new Date() objDate = new Date()
} else { }
objDate = new Date(y, parseInt(m) - 1, d) else {
objDate = new Date(y, Number.parseInt(m) - 1, d)
} }
let i let i
let leap = 0 let leap = 0
@ -837,10 +846,10 @@ const calendar = {
y = objDate.getFullYear() y = objDate.getFullYear()
m = objDate.getMonth() + 1 m = objDate.getMonth() + 1
d = objDate.getDate() d = objDate.getDate()
let offset = let offset
(Date.UTC(objDate.getFullYear(), objDate.getMonth(), objDate.getDate()) - = (Date.UTC(objDate.getFullYear(), objDate.getMonth(), objDate.getDate())
Date.UTC(1900, 0, 31)) / - Date.UTC(1900, 0, 31))
86400000 / 86400000
for (i = 1900; i < 2101 && offset > 0; i++) { for (i = 1900; i < 2101 && offset > 0; i++) {
temp = calendar.lYearDays(i) temp = calendar.lYearDays(i)
offset -= temp offset -= temp
@ -854,9 +863,9 @@ const calendar = {
const isTodayObj = new Date() const isTodayObj = new Date()
let isToday = false let isToday = false
if ( if (
isTodayObj.getFullYear() === +y && isTodayObj.getFullYear() === +y
isTodayObj.getMonth() + 1 === +m && && isTodayObj.getMonth() + 1 === +m
isTodayObj.getDate() === +d && isTodayObj.getDate() === +d
) { ) {
isToday = true isToday = true
} }
@ -879,18 +888,21 @@ const calendar = {
--i --i
isLeap = true isLeap = true
temp = calendar.leapDays(year) // 计算农历闰月天数 temp = calendar.leapDays(year) // 计算农历闰月天数
} else { }
else {
temp = calendar.monthDays(year, i) // 计算农历普通月天数 temp = calendar.monthDays(year, i) // 计算农历普通月天数
} }
// 解除闰月 // 解除闰月
if (isLeap === true && i === leap + 1) isLeap = false if (isLeap === true && i === leap + 1)
isLeap = false
offset -= temp offset -= temp
} }
// 闰月导致数组下标重叠取反 // 闰月导致数组下标重叠取反
if (offset === 0 && leap > 0 && i === leap + 1) { if (offset === 0 && leap > 0 && i === leap + 1) {
if (isLeap) { if (isLeap) {
isLeap = false isLeap = false
} else { }
else {
isLeap = true isLeap = true
--i --i
} }
@ -940,7 +952,7 @@ const calendar = {
lMonth: month, lMonth: month,
lDay: day, lDay: day,
Animal: calendar.getAnimal(year), Animal: calendar.getAnimal(year),
IMonthCn: (isLeap ? '\u95f0' : '') + calendar.toChinaMonth(month), IMonthCn: (isLeap ? '\u95F0' : '') + calendar.toChinaMonth(month),
IDayCn: calendar.toChinaDay(day), IDayCn: calendar.toChinaDay(day),
cYear: y, cYear: y,
cMonth: m, cMonth: m,
@ -948,13 +960,13 @@ const calendar = {
gzYear: gzY, gzYear: gzY,
gzMonth: gzM, gzMonth: gzM,
gzDay: gzD, gzDay: gzD,
isToday: isToday, isToday,
isLeap: isLeap, isLeap,
nWeek: nWeek, nWeek,
ncWeek: '\u661f\u671f' + cWeek, ncWeek: `\u661F\u671F${cWeek}`,
isTerm: isTerm, isTerm,
Term: Term, Term,
astro: astro astro,
} }
}, },
@ -967,18 +979,20 @@ const calendar = {
* @return JSON object * @return JSON object
* @eg:console.log(calendar.lunar2solar(1987,9,10)); * @eg:console.log(calendar.lunar2solar(1987,9,10));
*/ */
lunar2solar: function(y, m, d, isLeapMonth) { lunar2solar(y, m, d, isLeapMonth) {
// 参数区间1900.1.31~2100.12.1 // 参数区间1900.1.31~2100.12.1
isLeapMonth = !!isLeapMonth isLeapMonth = !!isLeapMonth
// let leapOffset = 0; // let leapOffset = 0;
const leapMonth = calendar.leapMonth(y) const leapMonth = calendar.leapMonth(y)
// let leapDay = calendar.leapDays(y); // let leapDay = calendar.leapDays(y);
if (isLeapMonth && leapMonth !== m) return -1 // 传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同 if (isLeapMonth && leapMonth !== m)
return -1 // 传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同
if ( if (
(+y === 2100 && +m === 12 && +d > 1) || (+y === 2100 && +m === 12 && +d > 1)
(+y === 1900 && +m === 1 && +d < 31) || (+y === 1900 && +m === 1 && +d < 31)
) ) {
return -1 // 超出了最大极限值 return -1
} // 超出了最大极限值
const day = calendar.monthDays(y, m) const day = calendar.monthDays(y, m)
let _day = day let _day = day
// bugFix 2016-9-25 // bugFix 2016-9-25
@ -986,7 +1000,8 @@ const calendar = {
if (isLeapMonth) { if (isLeapMonth) {
_day = calendar.leapDays(y, m) _day = calendar.leapDays(y, m)
} }
if (y < 1900 || y > 2100 || d > _day) return -1 // 参数合法性效验 if (y < 1900 || y > 2100 || d > _day)
return -1 // 参数合法性效验
// 计算农历的时间差 // 计算农历的时间差
let offset = 0 let offset = 0
@ -1007,7 +1022,8 @@ const calendar = {
offset += calendar.monthDays(y, i) offset += calendar.monthDays(y, i)
} }
// 转换闰月农历 需补充该年闰月的前一个月的时差 // 转换闰月农历 需补充该年闰月的前一个月的时差
if (isLeapMonth) offset += day if (isLeapMonth)
offset += day
// 1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点) // 1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点)
const stmap = Date.UTC(1900, 1, 30, 0, 0, 0) const stmap = Date.UTC(1900, 1, 30, 0, 0, 0)
const calObj = new Date((offset + d - 31) * 86400000 + stmap) const calObj = new Date((offset + d - 31) * 86400000 + stmap)
@ -1016,7 +1032,7 @@ const calendar = {
const cD = calObj.getUTCDate() const cD = calObj.getUTCDate()
return calendar.solar2lunar(cY, cM, cD) return calendar.solar2lunar(cY, cM, cD)
} },
} }
const { const {

2
src/components/calendar/plugins/solarLunar/index.d.ts vendored

@ -1 +1 @@
export {}; export {}

29
src/components/calendar/plugins/solarLunar/index.js

@ -2,7 +2,8 @@ import { dateUtil } from '../../utils/index'
import convertSolarLunar from './convertSolarLunar' import convertSolarLunar from './convertSolarLunar'
function getDateRow2Dict(dateInfo) { function getDateRow2Dict(dateInfo) {
if (!dateInfo) return dateInfo if (!dateInfo)
return dateInfo
if (typeof dateInfo === 'string' && dateInfo.includes('-')) { if (typeof dateInfo === 'string' && dateInfo.includes('-')) {
dateInfo = dateUtil.transformDateRow2Dict(dateInfo) dateInfo = dateUtil.transformDateRow2Dict(dateInfo)
} }
@ -15,45 +16,47 @@ export default () => {
beforeRender(calendarData = {}, calendarConfig = {}) { beforeRender(calendarData = {}, calendarConfig = {}) {
let { dates = [], selectedDates = [] } = calendarData let { dates = [], selectedDates = [] } = calendarData
if (calendarConfig.showLunar) { if (calendarConfig.showLunar) {
dates = dates.map(dataInfo => { dates = dates.map((dataInfo) => {
const { year, month, date } = dataInfo const { year, month, date } = dataInfo
return { return {
...dataInfo, ...dataInfo,
lunar: convertSolarLunar.solar2lunar(year, month, date) lunar: convertSolarLunar.solar2lunar(year, month, date),
} }
}) })
selectedDates = selectedDates.map(dataInfo => { selectedDates = selectedDates.map((dataInfo) => {
const { year, month, date } = dataInfo const { year, month, date } = dataInfo
return { return {
...dataInfo, ...dataInfo,
lunar: convertSolarLunar.solar2lunar(year, month, date) lunar: convertSolarLunar.solar2lunar(year, month, date),
} }
}) })
} }
return { return {
calendarData: { calendarData: {
...calendarData, ...calendarData,
dates: dates, dates,
selectedDates: selectedDates selectedDates,
}, },
calendarConfig calendarConfig,
} }
}, },
methods() { methods() {
return { return {
convertSolarLunar: dateInfo => { convertSolarLunar: (dateInfo) => {
dateInfo = getDateRow2Dict(dateInfo) dateInfo = getDateRow2Dict(dateInfo)
if (!dateInfo) return dateInfo if (!dateInfo)
return dateInfo
const { year, month, date } = dateInfo const { year, month, date } = dateInfo
return convertSolarLunar.solar2lunar(year, month, date) return convertSolarLunar.solar2lunar(year, month, date)
}, },
convertlLunar2Solar: (dateInfo, isLeapMonth) => { convertlLunar2Solar: (dateInfo, isLeapMonth) => {
dateInfo = getDateRow2Dict(dateInfo) dateInfo = getDateRow2Dict(dateInfo)
if (!dateInfo) return dateInfo if (!dateInfo)
return dateInfo
const { year, month, date } = dateInfo const { year, month, date } = dateInfo
return convertSolarLunar.lunar2solar(year, month, date, isLeapMonth) return convertSolarLunar.lunar2solar(year, month, date, isLeapMonth)
} },
} }
} },
} }
} }

126
src/components/calendar/plugins/time-range.js

@ -4,32 +4,32 @@
* @Date: 2020-10-08 21:22:09* * @Date: 2020-10-08 21:22:09*
* @Last Modified by: drfu * @Last Modified by: drfu
* @Last Modified time: 2020-10-11 13:56:32 * @Last Modified time: 2020-10-11 13:56:32
* */ */
import { renderCalendar } from '../render' import { renderCalendar } from '../render'
import { import {
logger,
dateUtil, dateUtil,
getCalendarConfig, getCalendarConfig,
getCalendarData getCalendarData,
logger,
} from '../utils/index' } from '../utils/index'
function pusheNextMonthDateArea( function pusheNextMonthDateArea(
dateInfo = {}, dateInfo = {},
startTimestamp, startTimestamp,
endTimestamp, endTimestamp,
selectedDates = [] selectedDates = [],
) { ) {
let tempOfSelectedDate = [...selectedDates] const tempOfSelectedDate = [...selectedDates]
const dates = dateUtil.calcDates(dateInfo.year, dateInfo.month) const dates = dateUtil.calcDates(dateInfo.year, dateInfo.month)
let datesLen = dates.length const datesLen = dates.length
for (let i = 0; i < datesLen; i++) { for (let i = 0; i < datesLen; i++) {
const date = dates[i] const date = dates[i]
const timeStamp = dateUtil.getTimeStamp(date) const timeStamp = dateUtil.getTimeStamp(date)
if (timeStamp <= endTimestamp && timeStamp >= startTimestamp) { if (timeStamp <= endTimestamp && timeStamp >= startTimestamp) {
tempOfSelectedDate.push({ tempOfSelectedDate.push({
...date, ...date,
choosed: true choosed: true,
}) })
} }
if (i === datesLen - 1 && timeStamp < endTimestamp) { if (i === datesLen - 1 && timeStamp < endTimestamp) {
@ -37,7 +37,7 @@ function pusheNextMonthDateArea(
dateUtil.getNextMonthInfo(date), dateUtil.getNextMonthInfo(date),
startTimestamp, startTimestamp,
endTimestamp, endTimestamp,
tempOfSelectedDate tempOfSelectedDate,
) )
} }
} }
@ -47,22 +47,22 @@ function pushPrevMonthDateArea(
dateInfo = {}, dateInfo = {},
startTimestamp, startTimestamp,
endTimestamp, endTimestamp,
selectedDates = [] selectedDates = [],
) { ) {
let tempOfSelectedDate = [...selectedDates] const tempOfSelectedDate = [...selectedDates]
const dates = dateUtil.sortDatesByTime( const dates = dateUtil.sortDatesByTime(
dateUtil.calcDates(dateInfo.year, dateInfo.month), dateUtil.calcDates(dateInfo.year, dateInfo.month),
'desc' 'desc',
) )
let datesLen = dates.length const datesLen = dates.length
let firstDate = dateUtil.getTimeStamp(dates[0]) const firstDate = dateUtil.getTimeStamp(dates[0])
for (let i = 0; i < datesLen; i++) { for (let i = 0; i < datesLen; i++) {
const date = dates[i] const date = dates[i]
const timeStamp = dateUtil.getTimeStamp(date) const timeStamp = dateUtil.getTimeStamp(date)
if (timeStamp >= startTimestamp && timeStamp <= endTimestamp) { if (timeStamp >= startTimestamp && timeStamp <= endTimestamp) {
tempOfSelectedDate.push({ tempOfSelectedDate.push({
...date, ...date,
choosed: true choosed: true,
}) })
} }
if (i === datesLen - 1 && firstDate > startTimestamp) { if (i === datesLen - 1 && firstDate > startTimestamp) {
@ -70,7 +70,7 @@ function pushPrevMonthDateArea(
dateUtil.getPrevMonthInfo(date), dateUtil.getPrevMonthInfo(date),
startTimestamp, startTimestamp,
endTimestamp, endTimestamp,
tempOfSelectedDate tempOfSelectedDate,
) )
} }
} }
@ -88,7 +88,7 @@ function calcDateWhenNotInOneMonth(info) {
dateUtil.getPrevMonthInfo(firstDate), dateUtil.getPrevMonthInfo(firstDate),
startTimestamp, startTimestamp,
endTimestamp, endTimestamp,
selectedDate selectedDate,
) )
} }
if (dateUtil.getTimeStamp(lastDate) < endTimestamp) { if (dateUtil.getTimeStamp(lastDate) < endTimestamp) {
@ -96,7 +96,7 @@ function calcDateWhenNotInOneMonth(info) {
dateUtil.getNextMonthInfo(lastDate), dateUtil.getNextMonthInfo(lastDate),
startTimestamp, startTimestamp,
endTimestamp, endTimestamp,
selectedDate selectedDate,
) )
} }
return [...selectedDate] return [...selectedDate]
@ -104,7 +104,7 @@ function calcDateWhenNotInOneMonth(info) {
/** /**
* 指定日期区域转时间戳 * 指定日期区域转时间戳
* @param {array} timearea 时间区域 * @param {Array} timearea 时间区域
*/ */
export function convertTimeRangeToTimestamp(timearea = []) { export function convertTimeRangeToTimestamp(timearea = []) {
const start = timearea[0].split('-') const start = timearea[0].split('-')
@ -121,40 +121,46 @@ export function convertTimeRangeToTimestamp(timearea = []) {
start, start,
end, end,
startTimestamp, startTimestamp,
endTimestamp endTimestamp,
} }
} }
/** /**
* 校验时间区域是否合法 * 校验时间区域是否合法
* @param {array} dateArea 时间区域 * @param {Array} dateArea 时间区域
*/ */
function validateTimeRange(dateArea) { function validateTimeRange(dateArea) {
const { const {
start, start,
end, end,
startTimestamp, startTimestamp,
endTimestamp endTimestamp,
} = convertTimeRangeToTimestamp(dateArea) } = convertTimeRangeToTimestamp(dateArea)
if (!start || !end) return if (!start || !end)
return
const startMonthDays = dateUtil.getDatesCountOfMonth(start[0], start[1]) const startMonthDays = dateUtil.getDatesCountOfMonth(start[0], start[1])
const endMonthDays = dateUtil.getDatesCountOfMonth(end[0], end[1]) const endMonthDays = dateUtil.getDatesCountOfMonth(end[0], end[1])
if (start[2] > startMonthDays || start[2] < 1) { if (start[2] > startMonthDays || start[2] < 1) {
logger.warn('enableArea() 开始日期错误,指定日期不在当前月份天数范围内') logger.warn('enableArea() 开始日期错误,指定日期不在当前月份天数范围内')
return false return false
} else if (start[1] > 12 || start[1] < 1) { }
else if (start[1] > 12 || start[1] < 1) {
logger.warn('enableArea() 开始日期错误,月份超出1-12月份') logger.warn('enableArea() 开始日期错误,月份超出1-12月份')
return false return false
} else if (end[2] > endMonthDays || end[2] < 1) { }
else if (end[2] > endMonthDays || end[2] < 1) {
logger.warn('enableArea() 截止日期错误,指定日期不在当前月份天数范围内') logger.warn('enableArea() 截止日期错误,指定日期不在当前月份天数范围内')
return false return false
} else if (end[1] > 12 || end[1] < 1) { }
else if (end[1] > 12 || end[1] < 1) {
logger.warn('enableArea() 截止日期错误,月份超出1-12月份') logger.warn('enableArea() 截止日期错误,月份超出1-12月份')
return false return false
} else if (startTimestamp > endTimestamp) { }
else if (startTimestamp > endTimestamp) {
logger.warn('enableArea()参数最小日期大于了最大日期') logger.warn('enableArea()参数最小日期大于了最大日期')
return false return false
} else { }
else {
return true return true
} }
} }
@ -166,26 +172,27 @@ export default () => {
const { const {
chooseAreaTimestamp = [], chooseAreaTimestamp = [],
dates = [], dates = [],
selectedDates = [] selectedDates = [],
} = calendarData } = calendarData
let __dates = dates let __dates = dates
let __selectedDates = selectedDates let __selectedDates = selectedDates
const [startDateTimestamp, endDateTimestamp] = chooseAreaTimestamp const [startDateTimestamp, endDateTimestamp] = chooseAreaTimestamp
if (chooseAreaTimestamp.length === 2) { if (chooseAreaTimestamp.length === 2) {
__selectedDates = [] __selectedDates = []
__dates = dates.map(d => { __dates = dates.map((d) => {
const date = { ...d } const date = { ...d }
const dateTimeStamp = dateUtil.getTimeStamp(date) const dateTimeStamp = dateUtil.getTimeStamp(date)
if ( if (
dateTimeStamp >= startDateTimestamp && dateTimeStamp >= startDateTimestamp
endDateTimestamp >= dateTimeStamp && endDateTimestamp >= dateTimeStamp
) { ) {
date.choosed = true date.choosed = true
__selectedDates.push(date) __selectedDates.push(date)
} else { }
else {
date.choosed = false date.choosed = false
__selectedDates = __selectedDates.filter( __selectedDates = __selectedDates.filter(
item => dateUtil.getTimeStamp(item) !== dateTimeStamp item => dateUtil.getTimeStamp(item) !== dateTimeStamp,
) )
} }
return date return date
@ -198,7 +205,7 @@ export default () => {
lastDate: __dates[__dates.length - 1], lastDate: __dates[__dates.length - 1],
startTimestamp: startDateTimestamp, startTimestamp: startDateTimestamp,
endTimestamp: endDateTimestamp, endTimestamp: endDateTimestamp,
selectedDate: __selectedDates selectedDate: __selectedDates,
}) })
} }
} }
@ -207,44 +214,47 @@ export default () => {
...calendarData, ...calendarData,
dates: __dates, dates: __dates,
selectedDates: dateUtil.sortDatesByTime( selectedDates: dateUtil.sortDatesByTime(
dateUtil.uniqueArrayByDate(__selectedDates) dateUtil.uniqueArrayByDate(__selectedDates),
) ),
}, },
calendarConfig calendarConfig,
} }
}, },
onTapDate(tapedDate, calendarData = {}, calendarConfig = {}) { onTapDate(tapedDate, calendarData = {}, calendarConfig = {}) {
if (!calendarConfig.chooseAreaMode) { if (!calendarConfig.chooseAreaMode) {
return { return {
calendarData, calendarData,
calendarConfig calendarConfig,
} }
} }
let { let {
tempChooseAreaTimestamp = [], tempChooseAreaTimestamp = [],
chooseAreaTimestamp: existChooseAreaTimestamp = [], chooseAreaTimestamp: existChooseAreaTimestamp = [],
selectedDates = [], selectedDates = [],
dates = [] dates = [],
} = calendarData } = calendarData
const timestamp = dateUtil.getTimeStamp(tapedDate) const timestamp = dateUtil.getTimeStamp(tapedDate)
let __dates = [...dates] const __dates = [...dates]
let __selectedDates = [...selectedDates] let __selectedDates = [...selectedDates]
if ( if (
tempChooseAreaTimestamp.length === 2 || tempChooseAreaTimestamp.length === 2
existChooseAreaTimestamp.length === 2 || existChooseAreaTimestamp.length === 2
) { ) {
tempChooseAreaTimestamp = [tapedDate] tempChooseAreaTimestamp = [tapedDate]
__selectedDates = [] __selectedDates = []
__dates.forEach(d => (d.choosed = false)) __dates.forEach(d => (d.choosed = false))
} else if (tempChooseAreaTimestamp.length === 1) { }
else if (tempChooseAreaTimestamp.length === 1) {
const preChoosedDate = tempChooseAreaTimestamp[0] const preChoosedDate = tempChooseAreaTimestamp[0]
const preTimestamp = dateUtil.getTimeStamp(preChoosedDate) const preTimestamp = dateUtil.getTimeStamp(preChoosedDate)
if (preTimestamp <= timestamp) { if (preTimestamp <= timestamp) {
tempChooseAreaTimestamp.push(tapedDate) tempChooseAreaTimestamp.push(tapedDate)
} else if (preTimestamp > timestamp) { }
else if (preTimestamp > timestamp) {
tempChooseAreaTimestamp.unshift(tapedDate) tempChooseAreaTimestamp.unshift(tapedDate)
} }
} else { }
else {
tempChooseAreaTimestamp = [tapedDate] tempChooseAreaTimestamp = [tapedDate]
} }
let chooseAreaTimestamp = [] let chooseAreaTimestamp = []
@ -260,46 +270,48 @@ export default () => {
chooseAreaTimestamp, chooseAreaTimestamp,
tempChooseAreaTimestamp, tempChooseAreaTimestamp,
dates: __dates, dates: __dates,
selectedDates: __selectedDates selectedDates: __selectedDates,
}, },
calendarConfig: { calendarConfig: {
...calendarConfig, ...calendarConfig,
multi: true multi: true,
} },
} }
}, },
methods(component) { methods(component) {
return { return {
/** /**
* 设置连续日期选择区域 * 设置连续日期选择区域
* @param {array} dateArea 区域开始结束日期数组 * @param {Array} dateArea 区域开始结束日期数组
*/ */
chooseDateArea: (dateArea = []) => { chooseDateArea: (dateArea = []) => {
if (dateArea.length === 1) { if (dateArea.length === 1) {
dateArea = dateArea.concat(dateArea) dateArea = dateArea.concat(dateArea)
} }
if (dateArea.length !== 2) return if (dateArea.length !== 2)
return
const isRight = validateTimeRange(dateArea) const isRight = validateTimeRange(dateArea)
if (!isRight) return if (!isRight)
return
const config = getCalendarConfig(component) || {} const config = getCalendarConfig(component) || {}
const { startTimestamp, endTimestamp } = convertTimeRangeToTimestamp( const { startTimestamp, endTimestamp } = convertTimeRangeToTimestamp(
dateArea dateArea,
) )
const existCalendarData = getCalendarData('calendar', component) const existCalendarData = getCalendarData('calendar', component)
return renderCalendar.call( return renderCalendar.call(
component, component,
{ {
...existCalendarData, ...existCalendarData,
chooseAreaTimestamp: [startTimestamp, endTimestamp] chooseAreaTimestamp: [startTimestamp, endTimestamp],
}, },
{ {
...config, ...config,
multi: true, multi: true,
chooseAreaMode: true chooseAreaMode: true,
} },
) )
} },
} }
} },
} }
} }

2
src/components/calendar/plugins/todo.d.ts vendored

@ -1 +1 @@
export {}; export {}

56
src/components/calendar/plugins/todo.js

@ -4,22 +4,24 @@
* @Date: 2020-10-08 21:22:09* * @Date: 2020-10-08 21:22:09*
* @Last Modified by: drfu * @Last Modified by: drfu
* @Last Modified time: 2020-10-11 14:23:02 * @Last Modified time: 2020-10-11 14:23:02
* */ */
import { getCalendarData, dateUtil } from '../utils/index'
import { renderCalendar } from '../render' import { renderCalendar } from '../render'
import { dateUtil, getCalendarData } from '../utils/index'
function updateDatePropertyOfTodoLabel(todos, dates, showLabelAlways) { function updateDatePropertyOfTodoLabel(todos, dates, showLabelAlways) {
const datesInfo = [...dates] const datesInfo = [...dates]
for (let todo of todos) { for (const todo of todos) {
let targetIdx = datesInfo.findIndex( const targetIdx = datesInfo.findIndex(
item => dateUtil.toTimeStr(item) === dateUtil.toTimeStr(todo) item => dateUtil.toTimeStr(item) === dateUtil.toTimeStr(todo),
) )
let target = datesInfo[targetIdx] const target = datesInfo[targetIdx]
if (!target) continue if (!target)
continue
if (showLabelAlways) { if (showLabelAlways) {
target.showTodoLabel = true target.showTodoLabel = true
} else { }
else {
target.showTodoLabel = !target.choosed target.showTodoLabel = !target.choosed
} }
if (target.showTodoLabel) { if (target.showTodoLabel) {
@ -38,14 +40,14 @@ export default () => {
const dateWithTodoInfo = updateDatePropertyOfTodoLabel( const dateWithTodoInfo = updateDatePropertyOfTodoLabel(
todos, todos,
dates, dates,
showLabelAlways showLabelAlways,
) )
return { return {
calendarData: { calendarData: {
...calendarData, ...calendarData,
dates: dateWithTodoInfo dates: dateWithTodoInfo,
}, },
calendarConfig calendarConfig,
} }
}, },
methods(component) { methods(component) {
@ -60,17 +62,17 @@ export default () => {
dotColor = '', dotColor = '',
pos = 'bottom', pos = 'bottom',
showLabelAlways, showLabelAlways,
dates: todoDates = [] dates: todoDates = [],
} = options } = options
const { todos = [] } = calendar const { todos = [] } = calendar
const tranformStr2NumOfTodo = todoDates.map(date => const tranformStr2NumOfTodo = todoDates.map(date =>
dateUtil.tranformStr2NumOfDate(date) dateUtil.tranformStr2NumOfDate(date),
) )
const calendarData = { const calendarData = {
dates: calendar.dates, dates: calendar.dates,
todos: dateUtil.uniqueArrayByDate( todos: dateUtil.uniqueArrayByDate(
todos.concat(tranformStr2NumOfTodo) todos.concat(tranformStr2NumOfTodo),
) ),
} }
if (!circle) { if (!circle) {
calendarData.todoLabelPos = pos calendarData.todoLabelPos = pos
@ -81,55 +83,55 @@ export default () => {
const existCalendarData = getCalendarData('calendar', component) const existCalendarData = getCalendarData('calendar', component)
return renderCalendar.call(component, { return renderCalendar.call(component, {
...existCalendarData, ...existCalendarData,
...calendarData ...calendarData,
}) })
}, },
deleteTodos(todos = []) { deleteTodos(todos = []) {
if (!(todos instanceof Array) || !todos.length) if (!(Array.isArray(todos)) || !todos.length)
return Promise.reject('deleteTodos()应为入参为非空数组') return Promise.reject('deleteTodos()应为入参为非空数组')
const existCalendarData = getCalendarData('calendar', component) const existCalendarData = getCalendarData('calendar', component)
const allTodos = existCalendarData.todos || [] const allTodos = existCalendarData.todos || []
const toDeleteTodos = todos.map(item => dateUtil.toTimeStr(item)) const toDeleteTodos = todos.map(item => dateUtil.toTimeStr(item))
const remainTodos = allTodos.filter( const remainTodos = allTodos.filter(
item => !toDeleteTodos.includes(dateUtil.toTimeStr(item)) item => !toDeleteTodos.includes(dateUtil.toTimeStr(item)),
) )
const { dates, curYear, curMonth } = existCalendarData const { dates, curYear, curMonth } = existCalendarData
const _dates = [...dates] const _dates = [...dates]
const currentMonthTodos = dateUtil.filterDatesByYM( const currentMonthTodos = dateUtil.filterDatesByYM(
{ {
year: curYear, year: curYear,
month: curMonth month: curMonth,
}, },
remainTodos remainTodos,
) )
_dates.forEach(item => { _dates.forEach((item) => {
item.showTodoLabel = false item.showTodoLabel = false
}) })
currentMonthTodos.forEach(item => { currentMonthTodos.forEach((item) => {
_dates[item.date - 1].showTodoLabel = !_dates[item.date - 1].choosed _dates[item.date - 1].showTodoLabel = !_dates[item.date - 1].choosed
}) })
return renderCalendar.call(component, { return renderCalendar.call(component, {
...existCalendarData, ...existCalendarData,
dates: _dates, dates: _dates,
todos: remainTodos todos: remainTodos,
}) })
}, },
clearTodos() { clearTodos() {
const existCalendarData = getCalendarData('calendar', component) const existCalendarData = getCalendarData('calendar', component)
const _dates = [...existCalendarData.dates] const _dates = [...existCalendarData.dates]
_dates.forEach(item => { _dates.forEach((item) => {
item.showTodoLabel = false item.showTodoLabel = false
}) })
return renderCalendar.call(component, { return renderCalendar.call(component, {
...existCalendarData, ...existCalendarData,
dates: _dates, dates: _dates,
todos: [] todos: [],
}) })
}, },
getTodos() { getTodos() {
return getCalendarData('calendar.todos', component) || [] return getCalendarData('calendar.todos', component) || []
} },
} }
} },
} }
} }

156
src/components/calendar/plugins/week.js

@ -4,16 +4,16 @@
* @Date: 2020-10-08 21:22:09* * @Date: 2020-10-08 21:22:09*
* @Last Modified by: drfu * @Last Modified by: drfu
* @Last Modified time: 2020-10-12 14:39:45 * @Last Modified time: 2020-10-12 14:39:45
* */ */
import { calcJumpData } from '../core'
import { renderCalendar } from '../render' import { renderCalendar } from '../render'
import { import {
dateUtil,
getCalendarConfig, getCalendarConfig,
getCalendarData, getCalendarData,
logger, logger,
dateUtil
} from '../utils/index' } from '../utils/index'
import { calcJumpData } from '../core'
/** /**
* 当月第一周所有日期 * 当月第一周所有日期
@ -21,7 +21,7 @@ import { calcJumpData } from '../core'
function firstWeekInMonth( function firstWeekInMonth(
target = {}, target = {},
calendarDates = [], calendarDates = [],
calendarConfig = {} calendarConfig = {},
) { ) {
const { firstDayOfWeek } = calendarConfig const { firstDayOfWeek } = calendarConfig
const firstDayOfWeekIsMon = firstDayOfWeek === 'Mon' const firstDayOfWeekIsMon = firstDayOfWeek === 'Mon'
@ -54,10 +54,11 @@ function lastWeekInMonth(target = {}, calendarDates = [], calendarConfig = {}) {
* 判断目标日期是否在某些指定日历内 * 判断目标日期是否在某些指定日历内
*/ */
function dateIsInDatesRange(target, dates) { function dateIsInDatesRange(target, dates) {
if (!target || !dates || !dates.length) return false if (!target || !dates || !dates.length)
return false
const targetDateStr = dateUtil.toTimeStr(target) const targetDateStr = dateUtil.toTimeStr(target)
let rst = false let rst = false
for (let date of dates) { for (const date of dates) {
const dateStr = dateUtil.toTimeStr(date) const dateStr = dateUtil.toTimeStr(date)
if (dateStr === targetDateStr) { if (dateStr === targetDateStr) {
rst = true rst = true
@ -73,17 +74,17 @@ function getDatesWhenTargetInFirstWeek(target, firstWeekDates) {
const prevMonthInfo = dateUtil.getPrevMonthInfo({ year, month }) const prevMonthInfo = dateUtil.getPrevMonthInfo({ year, month })
let lastMonthDatesCount = dateUtil.getDatesCountOfMonth( let lastMonthDatesCount = dateUtil.getDatesCountOfMonth(
prevMonthInfo.year, prevMonthInfo.year,
prevMonthInfo.month prevMonthInfo.month,
) )
let dates = firstWeekDates const dates = firstWeekDates
let firstWeekCount = firstWeekDates.length const firstWeekCount = firstWeekDates.length
for (let i = 0; i < 7 - firstWeekCount; i++) { for (let i = 0; i < 7 - firstWeekCount; i++) {
const week = dateUtil.getDayOfWeek(+year, +month, lastMonthDatesCount) const week = dateUtil.getDayOfWeek(+year, +month, lastMonthDatesCount)
dates.unshift({ dates.unshift({
year: prevMonthInfo.year, year: prevMonthInfo.year,
month: prevMonthInfo.month, month: prevMonthInfo.month,
date: lastMonthDatesCount, date: lastMonthDatesCount,
week week,
}) })
lastMonthDatesCount -= 1 lastMonthDatesCount -= 1
} }
@ -93,15 +94,15 @@ function getDatesWhenTargetInFirstWeek(target, firstWeekDates) {
function getDatesWhenTargetInLastWeek(target, lastWeekDates) { function getDatesWhenTargetInLastWeek(target, lastWeekDates) {
const { year, month } = target const { year, month } = target
const prevMonthInfo = dateUtil.getNextMonthInfo({ year, month }) const prevMonthInfo = dateUtil.getNextMonthInfo({ year, month })
let dates = lastWeekDates const dates = lastWeekDates
let lastWeekCount = lastWeekDates.length const lastWeekCount = lastWeekDates.length
for (let i = 0; i < 7 - lastWeekCount; i++) { for (let i = 0; i < 7 - lastWeekCount; i++) {
const week = dateUtil.getDayOfWeek(+year, +month, i + 1) const week = dateUtil.getDayOfWeek(+year, +month, i + 1)
dates.push({ dates.push({
year: prevMonthInfo.year, year: prevMonthInfo.year,
month: prevMonthInfo.month, month: prevMonthInfo.month,
date: i + 1, date: i + 1,
week week,
}) })
} }
return dates return dates
@ -115,23 +116,27 @@ function getDates(target, calendarDates = [], calendarConfig = {}) {
if (firstDayOfWeekIsMon) { if (firstDayOfWeekIsMon) {
const startIdx = date - (targetDay || 7) const startIdx = date - (targetDay || 7)
return calendarDates.splice(startIdx, 7) return calendarDates.splice(startIdx, 7)
} else { }
else {
const startIdx = date - targetDay - 1 const startIdx = date - targetDay - 1
return calendarDates.splice(startIdx, 7) return calendarDates.splice(startIdx, 7)
} }
} }
function getTargetWeekDates(target, calendarConfig) { function getTargetWeekDates(target, calendarConfig) {
if (!target) return if (!target)
return
const { year, month } = target const { year, month } = target
const calendarDates = dateUtil.calcDates(year, month) const calendarDates = dateUtil.calcDates(year, month)
const firstWeekDates = firstWeekInMonth(target, calendarDates, calendarConfig) const firstWeekDates = firstWeekInMonth(target, calendarDates, calendarConfig)
const lastWeekDates = lastWeekInMonth(target, calendarDates, calendarConfig) const lastWeekDates = lastWeekInMonth(target, calendarDates, calendarConfig)
if (dateIsInDatesRange(target, firstWeekDates)) { if (dateIsInDatesRange(target, firstWeekDates)) {
return getDatesWhenTargetInFirstWeek(target, firstWeekDates) return getDatesWhenTargetInFirstWeek(target, firstWeekDates)
} else if (dateIsInDatesRange(target, lastWeekDates)) { }
else if (dateIsInDatesRange(target, lastWeekDates)) {
return getDatesWhenTargetInLastWeek(target, lastWeekDates) return getDatesWhenTargetInLastWeek(target, lastWeekDates)
} else { }
else {
return getDates(target, calendarDates, calendarConfig) return getDates(target, calendarDates, calendarConfig)
} }
} }
@ -157,42 +162,44 @@ function calculateFirstDateOfCurrentWeek(calendarData = {}) {
function calculateNextWeekDates(calendarData = {}) { function calculateNextWeekDates(calendarData = {}) {
let { curYear, curMonth } = calendarData let { curYear, curMonth } = calendarData
let calendarDates = [] let calendarDates = []
let lastDateInThisWeek = calculateLastDateOfCurrentWeek(calendarData) const lastDateInThisWeek = calculateLastDateOfCurrentWeek(calendarData)
const { year: LYear, month: LMonth } = lastDateInThisWeek const { year: LYear, month: LMonth } = lastDateInThisWeek
if (curYear !== LYear || curMonth !== LMonth) { if (curYear !== LYear || curMonth !== LMonth) {
calendarDates = dateUtil.calcDates(LYear, LMonth) calendarDates = dateUtil.calcDates(LYear, LMonth)
curYear = LYear curYear = LYear
curMonth = LMonth curMonth = LMonth
} else { }
else {
calendarDates = dateUtil.calcDates(curYear, curMonth) calendarDates = dateUtil.calcDates(curYear, curMonth)
} }
const lastDateInThisMonth = dateUtil.getDatesCountOfMonth(curYear, curMonth) const lastDateInThisMonth = dateUtil.getDatesCountOfMonth(curYear, curMonth)
const count = lastDateInThisMonth - lastDateInThisWeek.date const count = lastDateInThisMonth - lastDateInThisWeek.date
const lastDateIdx = calendarDates.findIndex( const lastDateIdx = calendarDates.findIndex(
date => dateUtil.toTimeStr(date) === dateUtil.toTimeStr(lastDateInThisWeek) date => dateUtil.toTimeStr(date) === dateUtil.toTimeStr(lastDateInThisWeek),
) )
const startIdx = lastDateIdx + 1 const startIdx = lastDateIdx + 1
if (count >= 7) { if (count >= 7) {
return { return {
dates: calendarDates.splice(startIdx, 7), dates: calendarDates.splice(startIdx, 7),
year: curYear, year: curYear,
month: curMonth month: curMonth,
} }
} else { }
else {
const nextMonth = dateUtil.getNextMonthInfo({ const nextMonth = dateUtil.getNextMonthInfo({
year: curYear, year: curYear,
month: curMonth month: curMonth,
}) })
const { year, month } = nextMonth || {} const { year, month } = nextMonth || {}
const calendarDatesOfNextMonth = dateUtil.calcDates(year, month) const calendarDatesOfNextMonth = dateUtil.calcDates(year, month)
const remainDatesOfThisMonth = calendarDates.splice(startIdx) const remainDatesOfThisMonth = calendarDates.splice(startIdx)
const patchDatesOfNextMonth = calendarDatesOfNextMonth.splice( const patchDatesOfNextMonth = calendarDatesOfNextMonth.splice(
0, 0,
7 - remainDatesOfThisMonth.length 7 - remainDatesOfThisMonth.length,
) )
return { return {
dates: [...remainDatesOfThisMonth, ...patchDatesOfNextMonth], dates: [...remainDatesOfThisMonth, ...patchDatesOfNextMonth],
...nextMonth ...nextMonth,
} }
} }
} }
@ -202,43 +209,45 @@ function calculateNextWeekDates(calendarData = {}) {
*/ */
function calculatePrevWeekDates(calendarData = {}) { function calculatePrevWeekDates(calendarData = {}) {
let { curYear, curMonth } = calendarData let { curYear, curMonth } = calendarData
let firstDateInThisWeek = calculateFirstDateOfCurrentWeek(calendarData) const firstDateInThisWeek = calculateFirstDateOfCurrentWeek(calendarData)
let calendarDates = [] let calendarDates = []
const { year: FYear, month: FMonth } = firstDateInThisWeek const { year: FYear, month: FMonth } = firstDateInThisWeek
if (curYear !== FYear || curMonth !== FMonth) { if (curYear !== FYear || curMonth !== FMonth) {
calendarDates = dateUtil.calcDates(FYear, FMonth) calendarDates = dateUtil.calcDates(FYear, FMonth)
curYear = FYear curYear = FYear
curMonth = FMonth curMonth = FMonth
} else { }
else {
calendarDates = dateUtil.calcDates(curYear, curMonth) calendarDates = dateUtil.calcDates(curYear, curMonth)
} }
const firstDateIdx = calendarDates.findIndex( const firstDateIdx = calendarDates.findIndex(
date => dateUtil.toTimeStr(date) === dateUtil.toTimeStr(firstDateInThisWeek) date => dateUtil.toTimeStr(date) === dateUtil.toTimeStr(firstDateInThisWeek),
) )
if (firstDateIdx - 7 >= 0) { if (firstDateIdx - 7 >= 0) {
const startIdx = firstDateIdx - 7 const startIdx = firstDateIdx - 7
return { return {
dates: calendarDates.splice(startIdx, 7), dates: calendarDates.splice(startIdx, 7),
year: curYear, year: curYear,
month: curMonth month: curMonth,
} }
} else { }
else {
const prevMonth = dateUtil.getPrevMonthInfo({ const prevMonth = dateUtil.getPrevMonthInfo({
year: curYear, year: curYear,
month: curMonth month: curMonth,
}) })
const { year, month } = prevMonth || {} const { year, month } = prevMonth || {}
const calendarDatesOfPrevMonth = dateUtil.calcDates(year, month) const calendarDatesOfPrevMonth = dateUtil.calcDates(year, month)
const remainDatesOfThisMonth = calendarDates.splice( const remainDatesOfThisMonth = calendarDates.splice(
0, 0,
firstDateInThisWeek.date - 1 firstDateInThisWeek.date - 1,
) )
const patchDatesOfPrevMonth = calendarDatesOfPrevMonth.splice( const patchDatesOfPrevMonth = calendarDatesOfPrevMonth.splice(
-(7 - remainDatesOfThisMonth.length) -(7 - remainDatesOfThisMonth.length),
) )
return { return {
dates: [...patchDatesOfPrevMonth, ...remainDatesOfThisMonth], dates: [...patchDatesOfPrevMonth, ...remainDatesOfThisMonth],
...prevMonth ...prevMonth,
} }
} }
} }
@ -250,30 +259,30 @@ export default () => {
const { initializedWeekMode, selectedDates } = calendarData const { initializedWeekMode, selectedDates } = calendarData
if (calendarConfig.weekMode && !initializedWeekMode) { if (calendarConfig.weekMode && !initializedWeekMode) {
const { defaultDate } = calendarConfig const { defaultDate } = calendarConfig
const target = const target
(selectedDates && selectedDates[0]) || = (selectedDates && selectedDates[0])
(defaultDate && dateUtil.transformDateRow2Dict(defaultDate)) || || (defaultDate && dateUtil.transformDateRow2Dict(defaultDate))
dateUtil.todayFMD() || dateUtil.todayFMD()
const waitRenderData = this.methods( const waitRenderData = this.methods(
component component,
).__calcDatesWhenSwitchView('week', target) ).__calcDatesWhenSwitchView('week', target)
const { data, config } = waitRenderData || {} const { data, config } = waitRenderData || {}
const setSelectDates = this.methods( const setSelectDates = this.methods(
component component,
).__selectTargetDateWhenJump(target, data.dates, config) ).__selectTargetDateWhenJump(target, data.dates, config)
return { return {
calendarData: { calendarData: {
...data, ...data,
...setSelectDates, ...setSelectDates,
weeksCh: dateUtil.getWeekHeader(calendarConfig.firstDayOfWeek), weeksCh: dateUtil.getWeekHeader(calendarConfig.firstDayOfWeek),
initializedWeekMode: true initializedWeekMode: true,
}, },
calendarConfig calendarConfig,
} }
} }
return { return {
calendarData, calendarData,
calendarConfig calendarConfig,
} }
}, },
onSwitchCalendar(target = {}, calendarData = {}, component) { onSwitchCalendar(target = {}, calendarData = {}, component) {
@ -284,7 +293,8 @@ export default () => {
if (calendarConfig.weekMode) { if (calendarConfig.weekMode) {
if (direction === 'left') { if (direction === 'left') {
waitRenderData = calculateNextWeekDates(calendarData) waitRenderData = calculateNextWeekDates(calendarData)
} else { }
else {
waitRenderData = calculatePrevWeekDates(calendarData) waitRenderData = calculatePrevWeekDates(calendarData)
} }
const { dates, year, month } = waitRenderData const { dates, year, month } = waitRenderData
@ -292,7 +302,7 @@ export default () => {
...calendarData, ...calendarData,
dates, dates,
curYear: year || curYear, curYear: year || curYear,
curMonth: month || curMonth curMonth: month || curMonth,
} }
} }
return calendarData return calendarData
@ -304,8 +314,8 @@ export default () => {
const weekDates = dates.map((date, idx) => { const weekDates = dates.map((date, idx) => {
const tmp = { ...date } const tmp = { ...date }
tmp.id = idx tmp.id = idx
const isTarget = const isTarget
dateUtil.toTimeStr(target) === dateUtil.toTimeStr(tmp) = dateUtil.toTimeStr(target) === dateUtil.toTimeStr(tmp)
if (isTarget && !target.choosed && config.autoChoosedWhenJump) { if (isTarget && !target.choosed && config.autoChoosedWhenJump) {
tmp.choosed = true tmp.choosed = true
selectedDate = tmp selectedDate = tmp
@ -314,7 +324,7 @@ export default () => {
}) })
return { return {
dates: weekDates, dates: weekDates,
selectedDates: [selectedDate] selectedDates: [selectedDate],
} }
}, },
__calcDatesForWeekMode(target, config = {}, calendarData = {}) { __calcDatesForWeekMode(target, config = {}, calendarData = {}) {
@ -328,31 +338,31 @@ export default () => {
nextMonthGrids: null, nextMonthGrids: null,
dates: weekDates, dates: weekDates,
curYear: year, curYear: year,
curMonth: month curMonth: month,
}, },
config: { config: {
...config, ...config,
weekMode: true weekMode: true,
} },
} }
}, },
__calcDatesForMonthMode(target, config = {}, calendarData = {}) { __calcDatesForMonthMode(target, config = {}, calendarData = {}) {
const { year, month } = target || {} const { year, month } = target || {}
const waitRenderData = calcJumpData({ const waitRenderData = calcJumpData({
dateInfo: target, dateInfo: target,
config config,
}) })
return { return {
data: { data: {
...calendarData, ...calendarData,
...waitRenderData, ...waitRenderData,
curYear: year, curYear: year,
curMonth: month curMonth: month,
}, },
config: { config: {
...config, ...config,
weekMode: false weekMode: false,
} },
} }
}, },
/** /**
@ -369,18 +379,20 @@ export default () => {
selectedDates = [], selectedDates = [],
dates = [], dates = [],
curYear, curYear,
curMonth curMonth,
} = existCalendarData } = existCalendarData
const currentMonthSelected = selectedDates.filter( const currentMonthSelected = selectedDates.filter(
item => curYear === +item.year || curMonth === +item.month item => curYear === +item.year || curMonth === +item.month,
) )
let jumpTarget = {} let jumpTarget = {}
if (target) { if (target) {
jumpTarget = target jumpTarget = target
} else { }
else {
if (currentMonthSelected.length) { if (currentMonthSelected.length) {
jumpTarget = currentMonthSelected.pop() jumpTarget = currentMonthSelected.pop()
} else { }
else {
jumpTarget = dates[0] jumpTarget = dates[0]
} }
} }
@ -388,45 +400,47 @@ export default () => {
return this.methods(component).__calcDatesForWeekMode( return this.methods(component).__calcDatesForWeekMode(
jumpTarget, jumpTarget,
calendarConfig, calendarConfig,
existCalendarData existCalendarData,
) )
} else { }
else {
return this.methods(component).__calcDatesForMonthMode( return this.methods(component).__calcDatesForMonthMode(
jumpTarget, jumpTarget,
calendarConfig, calendarConfig,
existCalendarData existCalendarData,
) )
} }
}, },
weekModeJump: dateInfo => { weekModeJump: (dateInfo) => {
const target = dateInfo || dateUtil.todayFMD() const target = dateInfo || dateUtil.todayFMD()
const existCalendarData = getCalendarData('calendar', component) || {} const existCalendarData = getCalendarData('calendar', component) || {}
const waitRenderData = this.methods( const waitRenderData = this.methods(
component component,
).__calcDatesWhenSwitchView('week', target) ).__calcDatesWhenSwitchView('week', target)
const { data, config } = waitRenderData || {} const { data, config } = waitRenderData || {}
const setSelectDates = this.methods( const setSelectDates = this.methods(
component component,
).__selectTargetDateWhenJump(target, data.dates, config) ).__selectTargetDateWhenJump(target, data.dates, config)
return renderCalendar.call( return renderCalendar.call(
component, component,
{ {
...existCalendarData, ...existCalendarData,
...data, ...data,
...setSelectDates ...setSelectDates,
}, },
config config,
) )
}, },
switchView: (view, target) => { switchView: (view, target) => {
const waitRenderData = this.methods( const waitRenderData = this.methods(
component component,
).__calcDatesWhenSwitchView(view, target) ).__calcDatesWhenSwitchView(view, target)
const { data, config } = waitRenderData || {} const { data, config } = waitRenderData || {}
if (!data) return logger.warn('当前状态不能切换为周视图') if (!data)
return logger.warn('当前状态不能切换为周视图')
return renderCalendar.call(component, data, config) return renderCalendar.call(component, data, config)
} },
} }
} },
} }
} }

47
src/components/calendar/render.js

@ -1,29 +1,30 @@
import plugins from "./plugins/index"; import plugins from './plugins/index'
import { getCalendarConfig } from "./utils/index"; import { getCalendarConfig } from './utils/index'
/** /**
* 渲染日历 * 渲染日历
*/ */
export function renderCalendar(calendarData, calendarConfig) { export function renderCalendar(calendarData, calendarConfig) {
return new Promise((resolve) => { return new Promise((resolve) => {
const Component = this; const Component = this
if (Component.firstRender === void 0) { if (Component.firstRender === void 0) {
Component.firstRender = true; Component.firstRender = true
} else { }
Component.firstRender = false; else {
Component.firstRender = false
} }
const exitData = Component.data.calendar || {}; const exitData = Component.data.calendar || {}
for (let plugin of plugins.installed) { for (const plugin of plugins.installed) {
const [, p] = plugin; const [, p] = plugin
if (typeof p.beforeRender === "function") { if (typeof p.beforeRender === 'function') {
const { calendarData: newData, calendarConfig: newConfig } = const { calendarData: newData, calendarConfig: newConfig }
p.beforeRender( = p.beforeRender(
{ ...exitData, ...calendarData }, { ...exitData, ...calendarData },
calendarConfig || getCalendarConfig(Component), calendarConfig || getCalendarConfig(Component),
Component Component,
); )
calendarData = newData; calendarData = newData
calendarConfig = newConfig; calendarConfig = newConfig
} }
} }
@ -37,13 +38,13 @@ export function renderCalendar(calendarData, calendarConfig) {
calendar: calendarData, calendar: calendarData,
config: calendarConfig, config: calendarConfig,
firstRender: Component.firstRender, firstRender: Component.firstRender,
}; }
resolve(rst); resolve(rst)
if (Component.firstRender) { if (Component.firstRender) {
Component.triggerEvent("afterCalendarRender", rst); Component.triggerEvent('afterCalendarRender', rst)
Component.firstRender = false; Component.firstRender = false
} }
} },
); )
}); })
} }

290
src/components/calendar/utils/index.js

@ -1,16 +1,17 @@
import Logger from "./logger"; import Logger from './logger'
import WxData from "./wxData"; import WxData from './wxData'
let systemInfo; let systemInfo
export function getSystemInfo() { export function getSystemInfo() {
if (systemInfo) return systemInfo; if (systemInfo)
systemInfo = wx.getSystemInfoSync(); return systemInfo
return systemInfo; systemInfo = wx.getSystemInfoSync()
return systemInfo
} }
export function isIos() { export function isIos() {
const sys = getSystemInfo(); const sys = getSystemInfo()
return /iphone|ios/i.test(sys.platform); return /iphone|ios/i.test(sys.platform)
} }
class Gesture { class Gesture {
@ -20,69 +21,77 @@ class Gesture {
* @returns {boolean} 布尔值 * @returns {boolean} 布尔值
*/ */
isLeft(gesture = {}, touche = {}) { isLeft(gesture = {}, touche = {}) {
const { startX, startY } = gesture; const { startX, startY } = gesture
const deltaX = touche.clientX - startX; const deltaX = touche.clientX - startX
const deltaY = touche.clientY - startY; const deltaY = touche.clientY - startY
if (deltaX < -60 && deltaY < 20 && deltaY > -20) { if (deltaX < -60 && deltaY < 20 && deltaY > -20) {
return true; return true
} else { }
return false; else {
return false
} }
} }
/** /**
* 右滑 * 右滑
* @param {object} e 事件对象 * @param {object} e 事件对象
* @returns {boolean} 布尔值 * @returns {boolean} 布尔值
*/ */
isRight(gesture = {}, touche = {}) { isRight(gesture = {}, touche = {}) {
const { startX, startY } = gesture; const { startX, startY } = gesture
const deltaX = touche.clientX - startX; const deltaX = touche.clientX - startX
const deltaY = touche.clientY - startY; const deltaY = touche.clientY - startY
if (deltaX > 60 && deltaY < 20 && deltaY > -20) { if (deltaX > 60 && deltaY < 20 && deltaY > -20) {
return true; return true
} else { }
return false; else {
return false
} }
} }
} }
class DateUtil { class DateUtil {
newDate(year, month, date) { newDate(year, month, date) {
let cur = `${+year}-${+month}-${+date}`; let cur = `${+year}-${+month}-${+date}`
if (isIos()) { if (isIos()) {
cur = `${+year}/${+month}/${+date}`; cur = `${+year}/${+month}/${+date}`
} }
return new Date(cur); return new Date(cur)
} }
/** /**
* 计算指定日期时间戳 * 计算指定日期时间戳
* @param {object} date * @param {object} date
*/ */
getTimeStamp(dateInfo) { getTimeStamp(dateInfo) {
if (typeof dateInfo === "string") { if (typeof dateInfo === 'string') {
dateInfo = this.transformDateRow2Dict(dateInfo); dateInfo = this.transformDateRow2Dict(dateInfo)
} }
if (Object.prototype.toString.call(dateInfo) !== "[object Object]") return; if (Object.prototype.toString.call(dateInfo) !== '[object Object]')
const dateUtil = new DateUtil(); return
return dateUtil.newDate(dateInfo.year, dateInfo.month, dateInfo.date).getTime(); const dateUtil = new DateUtil()
} return dateUtil.newDate(dateInfo.year, dateInfo.month, dateInfo.date).getTime()
}
/** /**
* 计算指定月份共多少天 * 计算指定月份共多少天
* @param {number} year 年份 * @param {number} year 年份
* @param {number} month 月份 * @param {number} month 月份
*/ */
getDatesCountOfMonth(year, month) { getDatesCountOfMonth(year, month) {
return new Date(Date.UTC(year, month, 0)).getUTCDate(); return new Date(Date.UTC(year, month, 0)).getUTCDate()
} }
/** /**
* 计算指定月份第一天星期几 * 计算指定月份第一天星期几
* @param {number} year 年份 * @param {number} year 年份
* @param {number} month 月份 * @param {number} month 月份
*/ */
firstDayOfWeek(year, month) { firstDayOfWeek(year, month) {
return new Date(Date.UTC(year, month - 1, 1)).getUTCDay(); return new Date(Date.UTC(year, month - 1, 1)).getUTCDay()
} }
/** /**
* 计算指定日期星期几 * 计算指定日期星期几
* @param {number} year 年份 * @param {number} year 年份
@ -90,60 +99,68 @@ class DateUtil {
* @param {number} date 日期 * @param {number} date 日期
*/ */
getDayOfWeek(year, month, date) { getDayOfWeek(year, month, date) {
return new Date(Date.UTC(year, month - 1, date)).getUTCDay(); return new Date(Date.UTC(year, month - 1, date)).getUTCDay()
} }
todayFMD() { todayFMD() {
const _date = new Date(); const _date = new Date()
const year = _date.getFullYear(); const year = _date.getFullYear()
const month = _date.getMonth() + 1; const month = _date.getMonth() + 1
const date = _date.getDate(); const date = _date.getDate()
return { return {
year: +year, year: +year,
month: +month, month: +month,
date: +date, date: +date,
}; }
} }
todayTimestamp() { todayTimestamp() {
const { year, month, date } = this.todayFMD(); const { year, month, date } = this.todayFMD()
const timestamp = this.newDate(year, month, date).getTime(); const timestamp = this.newDate(year, month, date).getTime()
return timestamp; return timestamp
} }
toTimeStr(dateInfo = {}) { toTimeStr(dateInfo = {}) {
return `${+dateInfo.year}-${+dateInfo.month}-${+dateInfo.date}`; return `${+dateInfo.year}-${+dateInfo.month}-${+dateInfo.date}`
} }
transformDateRow2Dict(dateStr) { transformDateRow2Dict(dateStr) {
if (typeof dateStr === "string" && dateStr.includes("-")) { if (typeof dateStr === 'string' && dateStr.includes('-')) {
const [year, month, date] = dateStr.split("-"); const [year, month, date] = dateStr.split('-')
return this.tranformStr2NumOfDate({ return this.tranformStr2NumOfDate({
year, year,
month, month,
date, date,
}); })
} }
return {}; return {}
} }
tranformStr2NumOfDate(date = {}) { tranformStr2NumOfDate(date = {}) {
const target = { ...date }; const target = { ...date }
// 可能传入字符串 // 可能传入字符串
target.year = +target.year; target.year = +target.year
target.month = +target.month; target.month = +target.month
target.date = +target.date; target.date = +target.date
return target; return target
} }
sortDatesByTime(dates = [], sortType) { sortDatesByTime(dates = [], sortType) {
return dates.sort((a, b) => { return dates.sort((a, b) => {
const at = this.getTimeStamp(a); const at = this.getTimeStamp(a)
const bt = this.getTimeStamp(b); const bt = this.getTimeStamp(b)
if (at < bt && sortType !== "desc") { if (at < bt && sortType !== 'desc') {
return -1; return -1
} else { }
return 1; else {
return 1
} }
}); })
} }
getPrevMonthInfo(date = {}) { getPrevMonthInfo(date = {}) {
const prevMonthInfo = const prevMonthInfo
Number(date.month) > 1 = Number(date.month) > 1
? { ? {
year: +date.year, year: +date.year,
month: Number(date.month) - 1, month: Number(date.month) - 1,
@ -151,12 +168,13 @@ class DateUtil {
: { : {
year: Number(date.year) - 1, year: Number(date.year) - 1,
month: 12, month: 12,
}; }
return prevMonthInfo; return prevMonthInfo
} }
getNextMonthInfo(date = {}) { getNextMonthInfo(date = {}) {
const nextMonthInfo = const nextMonthInfo
Number(date.month) < 12 = Number(date.month) < 12
? { ? {
year: +date.year, year: +date.year,
month: Number(date.month) + 1, month: Number(date.month) + 1,
@ -164,30 +182,34 @@ class DateUtil {
: { : {
year: Number(date.year) + 1, year: Number(date.year) + 1,
month: 1, month: 1,
}; }
return nextMonthInfo; return nextMonthInfo
} }
getPrevYearInfo(date = {}) { getPrevYearInfo(date = {}) {
return { return {
year: Number(date.year) - 1, year: Number(date.year) - 1,
month: +date.month, month: +date.month,
}; }
} }
getNextYearInfo(date = {}) { getNextYearInfo(date = {}) {
return { return {
year: Number(date.year) + 1, year: Number(date.year) + 1,
month: +date.month, month: +date.month,
}; }
} }
findDateIndexInArray(target, dates) { findDateIndexInArray(target, dates) {
return dates.findIndex((item) => dateUtil.toTimeStr(item) === dateUtil.toTimeStr(target)); return dates.findIndex(item => dateUtil.toTimeStr(item) === dateUtil.toTimeStr(target))
} }
calcDates(year, month) { calcDates(year, month) {
const datesCount = this.getDatesCountOfMonth(year, month); const datesCount = this.getDatesCountOfMonth(year, month)
const dates = []; const dates = []
const today = dateUtil.todayFMD(); const today = dateUtil.todayFMD()
for (let i = 1; i <= datesCount; i++) { for (let i = 1; i <= datesCount; i++) {
const week = dateUtil.getDayOfWeek(+year, +month, i); const week = dateUtil.getDayOfWeek(+year, +month, i)
const date = { const date = {
year: +year, year: +year,
id: i - 1, id: i - 1,
@ -195,45 +217,48 @@ class DateUtil {
date: i, date: i,
week, week,
isToday: +today.year === +year && +today.month === +month && i === +today.date, isToday: +today.year === +year && +today.month === +month && i === +today.date,
}; }
dates.push(date); dates.push(date)
} }
return dates; return dates
} }
/** /**
* 日期数组根据日期去重 * 日期数组根据日期去重
* @param {array} array 数组 * @param {Array} array 数组
*/ */
uniqueArrayByDate(array = []) { uniqueArrayByDate(array = []) {
let uniqueObject = {}; const uniqueObject = {}
let uniqueArray = []; const uniqueArray = []
array.forEach((item) => { array.forEach((item) => {
uniqueObject[dateUtil.toTimeStr(item)] = item; uniqueObject[dateUtil.toTimeStr(item)] = item
}); })
for (let i in uniqueObject) { for (const i in uniqueObject) {
uniqueArray.push(uniqueObject[i]); uniqueArray.push(uniqueObject[i])
} }
return uniqueArray; return uniqueArray
} }
/** /**
* 筛选指定年月日期 * 筛选指定年月日期
* @param {object} target 指定年月 * @param {object} target 指定年月
* @param {array} dates 待筛选日期 * @param {Array} dates 待筛选日期
*/ */
filterDatesByYM(target, dates) { filterDatesByYM(target, dates) {
if (target) { if (target) {
const { year, month } = target; const { year, month } = target
const _dates = dates.filter((item) => +item.year === +year && +item.month === +month); const _dates = dates.filter(item => +item.year === +year && +item.month === +month)
return _dates; return _dates
} }
return dates; return dates
} }
getWeekHeader(firstDayOfWeek) { getWeekHeader(firstDayOfWeek) {
let weeksCh = ["日", "一", "二", "三", "四", "五", "六"]; let weeksCh = ['日', '一', '二', '三', '四', '五', '六']
if (firstDayOfWeek === "Mon") { if (firstDayOfWeek === 'Mon') {
weeksCh = ["一", "二", "三", "四", "五", "六", "日"]; weeksCh = ['一', '二', '三', '四', '五', '六', '日']
} }
return weeksCh; return weeksCh
} }
} }
@ -241,35 +266,38 @@ class DateUtil {
* 获取当前页面实例 * 获取当前页面实例
*/ */
export function getCurrentPage() { export function getCurrentPage() {
const pages = getCurrentPages() || []; const pages = getCurrentPages() || []
const last = pages.length - 1; const last = pages.length - 1
return pages[last] || {}; return pages[last] || {}
} }
export function getComponentById(componentId) { export function getComponentById(componentId) {
const logger = new Logger(); const logger = new Logger()
let page = getCurrentPage() || {}; const page = getCurrentPage() || {}
if (page.selectComponent && typeof page.selectComponent === "function") { if (page.selectComponent && typeof page.selectComponent === 'function') {
if (componentId) { if (componentId) {
return page.selectComponent(componentId); return page.selectComponent(componentId)
} else { }
logger.warn("请传入组件ID"); else {
logger.warn('请传入组件ID')
} }
} else { }
logger.warn("该基础库暂不支持多个小程序日历组件"); else {
logger.warn('该基础库暂不支持多个小程序日历组件')
} }
} }
export const logger = new Logger(); export const logger = new Logger()
export const calendarGesture = new Gesture(); export const calendarGesture = new Gesture()
export const dateUtil = new DateUtil(); export const dateUtil = new DateUtil()
export const getCalendarData = (key, component) => new WxData(component).getData(key); export const getCalendarData = (key, component) => new WxData(component).getData(key)
export const setCalendarData = (data, component) => new WxData(component).setData(data); export const setCalendarData = (data, component) => new WxData(component).setData(data)
export const getCalendarConfig = (component) => getCalendarData("config", component); export const getCalendarConfig = component => getCalendarData('config', component)
export const setCalendarConfig = (config, component) => export function setCalendarConfig(config, component) {
setCalendarData( return setCalendarData(
{ {
config, config,
}, },
component, component,
); )
}

18
src/components/calendar/utils/logger.js

@ -1,23 +1,25 @@
export default class Logger { export default class Logger {
info(msg) { info(msg) {
console.log( console.log(
'%cInfo: %c' + msg, `%cInfo: %c${msg}`,
'color:#FF0080;font-weight:bold', 'color:#FF0080;font-weight:bold',
'color: #FF509B' 'color: #FF509B',
) )
} }
warn(msg) { warn(msg) {
console.log( console.log(
'%cWarn: %c' + msg, `%cWarn: %c${msg}`,
'color:#FF6600;font-weight:bold', 'color:#FF6600;font-weight:bold',
'color: #FF9933' 'color: #FF9933',
) )
} }
tips(msg) { tips(msg) {
console.log( console.log(
'%cTips: %c' + msg, `%cTips: %c${msg}`,
'color:#00B200;font-weight:bold', 'color:#00B200;font-weight:bold',
'color: #00CC33' 'color: #00CC33',
) )
} }
} }

17
src/components/calendar/utils/wxData.js

@ -1,23 +1,28 @@
class WxData { class WxData {
constructor(component) { constructor(component) {
this.Component = component this.Component = component
} }
getData(key) { getData(key) {
const data = this.Component.data const data = this.Component.data
if (!key) return data if (!key)
return data
if (key.includes('.')) { if (key.includes('.')) {
let keys = key.split('.') const keys = key.split('.')
const tmp = keys.reduce((prev, next) => { const tmp = keys.reduce((prev, next) => {
return prev[next] return prev[next]
}, data) }, data)
return tmp return tmp
} else { }
else {
return this.Component.data[key] return this.Component.data[key]
} }
} }
setData(data) { setData(data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!data) return reject('no data to set') if (!data)
return reject('no data to set')
if (typeof data === 'object') { if (typeof data === 'object') {
this.Component.setData(data, () => { this.Component.setData(data, () => {
resolve(data) resolve(data)

148
src/components/customPoster/README.md

@ -28,28 +28,28 @@ const data = {
}, },
elements: [ elements: [
{ {
id: 'circle-name', 'id': 'circle-name',
desc: '圈名称', 'desc': '圈名称',
type: 1, 'type': 1,
text: '治疗讨论', 'text': '治疗讨论',
font: '宋体', 'font': '宋体',
'font-size': '42', 'font-size': '42',
color: '#FFFFFF', 'color': '#FFFFFF',
'single-line': true, 'single-line': true,
halign: 'center', 'halign': 'center',
top: '106', 'top': '106',
}, },
{ {
id: 'master-name', 'id': 'master-name',
desc: '专家名称', 'desc': '专家名称',
type: 1, 'type': 1,
text: '健康小贴士', 'text': '健康小贴士',
font: '宋体', 'font': '宋体',
'font-size': '38', 'font-size': '38',
color: '#FFFFFF', 'color': '#FFFFFF',
'single-line': true, 'single-line': true,
halign: 'center', 'halign': 'center',
top: '237', 'top': '237',
}, },
{ {
id: 'master-avatar', id: 'master-avatar',
@ -64,72 +64,72 @@ const data = {
top: '328', top: '328',
}, },
{ {
id: 'note-content', 'id': 'note-content',
desc: '动态内容', 'desc': '动态内容',
type: 1, 'type': 1,
text: '11月5日上海组织进口博览会CIIE大会,邀请大家来我们的展馆现场交流。', 'text': '11月5日上海组织进口博览会CIIE大会,邀请大家来我们的展馆现场交流。',
font: '宋体', 'font': '宋体',
'font-size': '45', 'font-size': '45',
color: '#18191A', 'color': '#18191A',
width: '630', 'width': '630',
height: '348', 'height': '348',
left: '60', 'left': '60',
top: '495', 'top': '495',
}, },
{ {
id: 'note-title', 'id': 'note-title',
desc: '长文标题', 'desc': '长文标题',
type: 1, 'type': 1,
text: '', 'text': '',
font: '宋体', 'font': '宋体',
'font-size': '42', 'font-size': '42',
color: '#18191A', 'color': '#18191A',
width: '659', 'width': '659',
height: '116', 'height': '116',
left: '46', 'left': '46',
top: '495', 'top': '495',
'font-weight': 'bold', 'font-weight': 'bold',
}, },
{ {
id: 'note-summary', 'id': 'note-summary',
desc: '长文摘要 ', 'desc': '长文摘要 ',
type: 1, 'type': 1,
text: '', 'text': '',
font: '宋体', 'font': '宋体',
'font-size': '42', 'font-size': '42',
color: '#18191A', 'color': '#18191A',
width: '672', 'width': '672',
height: '232', 'height': '232',
left: '39', 'left': '39',
top: '646', 'top': '646',
}, },
{ {
id: 'note-more', 'id': 'note-more',
desc: '还有', 'desc': '还有',
type: 1, 'type': 1,
text: '还有3条精彩附件>', 'text': '还有3条精彩附件>',
font: '宋体', 'font': '宋体',
'font-size': '31', 'font-size': '31',
color: '#666666', 'color': '#666666',
'single-line': true, 'single-line': true,
width: '292', 'width': '292',
height: '46', 'height': '46',
left: '60', 'left': '60',
top: '1024', 'top': '1024',
}, },
{ {
id: 'scanText', 'id': 'scanText',
desc: '扫描二维码查看详情', 'desc': '扫描二维码查看详情',
type: 1, 'type': 1,
text: '扫描二维码查看详情', 'text': '扫描二维码查看详情',
font: '宋体', 'font': '宋体',
'font-size': '31', 'font-size': '31',
color: '#666666', 'color': '#666666',
'single-line': true, 'single-line': true,
width: '279', 'width': '279',
height: '43', 'height': '43',
left: '60', 'left': '60',
top: '1087', 'top': '1087',
}, },
{ {
id: 'note-qrcode', id: 'note-qrcode',
@ -143,16 +143,16 @@ const data = {
top: '1012', top: '1012',
}, },
{ {
id: 'brand', 'id': 'brand',
desc: 'brand×华秉科技', 'desc': 'brand×华秉科技',
type: 1, 'type': 1,
text: '做企业数字化转型的亲密伙伴×华秉科技', 'text': '做企业数字化转型的亲密伙伴×华秉科技',
font: '宋体', 'font': '宋体',
'font-size': '24', 'font-size': '24',
color: '#B2B3B4', 'color': '#B2B3B4',
'single-line': true, 'single-line': true,
halign: 'center', 'halign': 'center',
top: '1192', 'top': '1192',
}, },
], ],
}, },

88
src/components/customPoster/index.js

@ -1,4 +1,4 @@
import Wxml2Canvas from "./wxml2canvas/index.js"; // 根据具体路径修改,node_modules会被忽略 import Wxml2Canvas from './wxml2canvas/index.js' // 根据具体路径修改,node_modules会被忽略
Component({ Component({
properties: { properties: {
@ -6,24 +6,24 @@ Component({
type: Object, type: Object,
observer(newVal, _olVal) { observer(newVal, _olVal) {
if (Object.keys(newVal).length > 0) { if (Object.keys(newVal).length > 0) {
this.paramsFormat(newVal); this.paramsFormat(newVal)
this.setData({ this.setData({
width: newVal.body.width, width: newVal.body.width,
height: newVal.body.height, height: newVal.body.height,
bgImg: newVal.body.bgImg, bgImg: newVal.body.bgImg,
elementsMp: newVal.elements, elementsMp: newVal.elements,
}); })
this.drawImage(); this.drawImage()
} }
}, },
}, },
}, },
data: { data: {
imgUrl: "", imgUrl: '',
width: "", width: '',
height: "", height: '',
imgheight: "", imgheight: '',
bgImg: "", bgImg: '',
elementsMp: [], elementsMp: [],
}, },
lifetimes: { lifetimes: {
@ -34,68 +34,70 @@ Component({
params.elements.forEach((item) => { params.elements.forEach((item) => {
if (item.type === 0) { if (item.type === 0) {
// 图片居中 // 图片居中
if (item.halign === "center") { if (item.halign === 'center') {
item.left = (params.body.width - item.width) / 2; item.left = (params.body.width - item.width) / 2
} }
} else { }
item.text = item.text.replace(/[\r\n]/g, ""); else {
item.text = item.text.replace(/[\r\n]/g, '')
// 文字居中(使文字标签宽度等于画布宽度,文字加上居中的className) // 文字居中(使文字标签宽度等于画布宽度,文字加上居中的className)
if (item.halign === "center") { if (item.halign === 'center') {
item.width = item.width || params.body.width; item.width = item.width || params.body.width
item.left = (params.body.width - item.width) / 2; item.left = (params.body.width - item.width) / 2
}
if (item.halign === 'right') {
item.width = params.body.width
} }
if (item.halign === "right") { if (item.id === 'shareText' && item.text.length > 30) {
item.width = params.body.width; item.text = `${item.text.slice(0, 30)}...`
} }
if (item.id === "shareText" && item.text.length > 30) { if (item.id === 'note-title' && item.text.length > 28) {
item.text = item.text.slice(0, 30) + "..."; item.text = `${item.text.slice(0, 28)}...`
} }
if (item.id === "note-title" && item.text.length > 28) { if (item.id === 'note-content' && item.text.length > 90) {
item.text = item.text.slice(0, 28) + "..."; item.text = `${item.text.slice(0, 90)}...`
} }
if (item.id === "note-content" && item.text.length > 90) { const len = params.elements.some(x => x.id === 'note-title' && x.text.length)
item.text = item.text.slice(0, 90) + "..."; if (len && item.id === 'note-summary' && item.text.length > 62) {
item.text = `${item.text.slice(0, 62)}...`
} }
let len = params.elements.some((x) => x.id === "note-title" && x.text.length); else if (item.id === 'note-summary' && item.text.length > 76) {
if (len && item.id === "note-summary" && item.text.length > 62) { item.text = `${item.text.slice(0, 76)}...`
item.text = item.text.slice(0, 62) + "...";
} else if (item.id === "note-summary" && item.text.length > 76) {
item.text = item.text.slice(0, 76) + "...";
} }
} }
}); })
}, },
drawImage() { drawImage() {
let self = this; const self = this
this.drawImage1 = new Wxml2Canvas({ this.drawImage1 = new Wxml2Canvas({
obj: self, obj: self,
width: this.data.width, // 宽, 以iphone6为基准,传具体数值,其它机型自动适配 width: this.data.width, // 宽, 以iphone6为基准,传具体数值,其它机型自动适配
height: this.data.height, // 高 height: this.data.height, // 高
element: "canvas1", element: 'canvas1',
background: "transparent", background: 'transparent',
progress(percent) {}, progress(percent) {},
finish(url) { finish(url) {
self.setData({ self.setData({
imgUrl: url, imgUrl: url,
}); })
self.triggerEvent("finish", url); self.triggerEvent('finish', url)
}, },
error(res) {}, error(res) {},
}); })
let data = { const data = {
list: [ list: [
{ {
type: "wxml", type: 'wxml',
class: "#canvas-bill-body-mp .draw_canvas", class: '#canvas-bill-body-mp .draw_canvas',
limit: "#canvas-bill-body-mp", limit: '#canvas-bill-body-mp',
x: 0, x: 0,
y: 0, y: 0,
}, },
], ],
}; }
this.drawImage1.draw(data); this.drawImage1.draw(data)
}, },
}, },
}); })

1968
src/components/customPoster/wxml2canvas/index.js

File diff suppressed because it is too large Load Diff

148
src/components/customTable/README.md

@ -28,28 +28,28 @@ const data = {
}, },
elements: [ elements: [
{ {
id: 'circle-name', 'id': 'circle-name',
desc: '圈名称', 'desc': '圈名称',
type: 1, 'type': 1,
text: '治疗讨论', 'text': '治疗讨论',
font: '宋体', 'font': '宋体',
'font-size': '42', 'font-size': '42',
color: '#FFFFFF', 'color': '#FFFFFF',
'single-line': true, 'single-line': true,
halign: 'center', 'halign': 'center',
top: '106', 'top': '106',
}, },
{ {
id: 'master-name', 'id': 'master-name',
desc: '专家名称', 'desc': '专家名称',
type: 1, 'type': 1,
text: '健康小贴士', 'text': '健康小贴士',
font: '宋体', 'font': '宋体',
'font-size': '38', 'font-size': '38',
color: '#FFFFFF', 'color': '#FFFFFF',
'single-line': true, 'single-line': true,
halign: 'center', 'halign': 'center',
top: '237', 'top': '237',
}, },
{ {
id: 'master-avatar', id: 'master-avatar',
@ -64,72 +64,72 @@ const data = {
top: '328', top: '328',
}, },
{ {
id: 'note-content', 'id': 'note-content',
desc: '动态内容', 'desc': '动态内容',
type: 1, 'type': 1,
text: '11月5日上海组织进口博览会CIIE大会,邀请大家来我们的展馆现场交流。', 'text': '11月5日上海组织进口博览会CIIE大会,邀请大家来我们的展馆现场交流。',
font: '宋体', 'font': '宋体',
'font-size': '45', 'font-size': '45',
color: '#18191A', 'color': '#18191A',
width: '630', 'width': '630',
height: '348', 'height': '348',
left: '60', 'left': '60',
top: '495', 'top': '495',
}, },
{ {
id: 'note-title', 'id': 'note-title',
desc: '长文标题', 'desc': '长文标题',
type: 1, 'type': 1,
text: '', 'text': '',
font: '宋体', 'font': '宋体',
'font-size': '42', 'font-size': '42',
color: '#18191A', 'color': '#18191A',
width: '659', 'width': '659',
height: '116', 'height': '116',
left: '46', 'left': '46',
top: '495', 'top': '495',
'font-weight': 'bold', 'font-weight': 'bold',
}, },
{ {
id: 'note-summary', 'id': 'note-summary',
desc: '长文摘要 ', 'desc': '长文摘要 ',
type: 1, 'type': 1,
text: '', 'text': '',
font: '宋体', 'font': '宋体',
'font-size': '42', 'font-size': '42',
color: '#18191A', 'color': '#18191A',
width: '672', 'width': '672',
height: '232', 'height': '232',
left: '39', 'left': '39',
top: '646', 'top': '646',
}, },
{ {
id: 'note-more', 'id': 'note-more',
desc: '还有', 'desc': '还有',
type: 1, 'type': 1,
text: '还有3条精彩附件>', 'text': '还有3条精彩附件>',
font: '宋体', 'font': '宋体',
'font-size': '31', 'font-size': '31',
color: '#666666', 'color': '#666666',
'single-line': true, 'single-line': true,
width: '292', 'width': '292',
height: '46', 'height': '46',
left: '60', 'left': '60',
top: '1024', 'top': '1024',
}, },
{ {
id: 'scanText', 'id': 'scanText',
desc: '扫描二维码查看详情', 'desc': '扫描二维码查看详情',
type: 1, 'type': 1,
text: '扫描二维码查看详情', 'text': '扫描二维码查看详情',
font: '宋体', 'font': '宋体',
'font-size': '31', 'font-size': '31',
color: '#666666', 'color': '#666666',
'single-line': true, 'single-line': true,
width: '279', 'width': '279',
height: '43', 'height': '43',
left: '60', 'left': '60',
top: '1087', 'top': '1087',
}, },
{ {
id: 'note-qrcode', id: 'note-qrcode',
@ -143,16 +143,16 @@ const data = {
top: '1012', top: '1012',
}, },
{ {
id: 'brand', 'id': 'brand',
desc: 'brand×华秉科技', 'desc': 'brand×华秉科技',
type: 1, 'type': 1,
text: '做企业数字化转型的亲密伙伴×华秉科技', 'text': '做企业数字化转型的亲密伙伴×华秉科技',
font: '宋体', 'font': '宋体',
'font-size': '24', 'font-size': '24',
color: '#B2B3B4', 'color': '#B2B3B4',
'single-line': true, 'single-line': true,
halign: 'center', 'halign': 'center',
top: '1192', 'top': '1192',
}, },
], ],
}, },

203
src/components/customTable/index.js

@ -1,5 +1,6 @@
const app = getApp(); import Wxml2Canvas from './wxml2canvas/index.js'
import Wxml2Canvas from "./wxml2canvas/index.js"; // 根据具体路径修改,node_modules会被忽略
const app = getApp() // 根据具体路径修改,node_modules会被忽略
Component({ Component({
properties: { properties: {
@ -7,193 +8,193 @@ Component({
type: Object, type: Object,
observer(newVal, _olVal) { observer(newVal, _olVal) {
if (Object.keys(newVal).length > 0) { if (Object.keys(newVal).length > 0) {
this.drawImage1(); this.drawImage1()
} }
}, },
}, },
}, },
data: { data: {
imageUrl: app.globalData.imageUrl, imageUrl: app.globalData.imageUrl,
imgUrl: "", imgUrl: '',
width: "626", width: '626',
height: "980", height: '980',
imgheight: "", imgheight: '',
bgImg: "", bgImg: '',
elementsMp: [], elementsMp: [],
tableData: [ tableData: [
{ {
title: "说话", title: '说话',
key: "TalkingScore", key: 'TalkingScore',
list: [ list: [
{ {
id: "1", id: '1',
title: "正常", title: '正常',
}, },
{ {
id: "2", id: '2',
title: "间或有点含糊或有鼻音", title: '间或有点含糊或有鼻音',
}, },
{ {
id: "3", id: '3',
title: "经常含糊不清或者有鼻音,但是别人还能听懂", title: '经常含糊不清或者有鼻音,但是别人还能听懂',
}, },
{ {
id: "4", id: '4',
title: "别人听不太懂", title: '别人听不太懂',
}, },
], ],
}, },
{ {
title: "咀嚼", title: '咀嚼',
key: "ChewScore", key: 'ChewScore',
list: [ list: [
{ {
id: "1", id: '1',
title: "正常", title: '正常',
}, },
{ {
id: "2", id: '2',
title: "咀嚼固体食物会感到疲劳", title: '咀嚼固体食物会感到疲劳',
}, },
{ {
id: "3", id: '3',
title: "咀嚼松软食物会感到疲劳", title: '咀嚼松软食物会感到疲劳',
}, },
{ {
id: "4", id: '4',
title: "使用喂食管进食,如鼻胃管胃肠管等", title: '使用喂食管进食,如鼻胃管胃肠管等',
}, },
], ],
}, },
{ {
title: "吞咽", title: '吞咽',
key: "SwallowScore", key: 'SwallowScore',
list: [ list: [
{ {
id: "1", id: '1',
title: "正常", title: '正常',
}, },
{ {
id: "2", id: '2',
title: "偶尔会噎到", title: '偶尔会噎到',
}, },
{ {
id: "3", id: '3',
title: "经常会噎到,因而需要改变饮食习惯", title: '经常会噎到,因而需要改变饮食习惯',
}, },
{ {
id: "4", id: '4',
title: "使用喂食管进食,如鼻胃管胃肠管等", title: '使用喂食管进食,如鼻胃管胃肠管等',
}, },
], ],
}, },
{ {
title: "呼吸", title: '呼吸',
key: "BreathScore", key: 'BreathScore',
list: [ list: [
{ {
id: "1", id: '1',
title: "正常", title: '正常',
}, },
{ {
id: "2", id: '2',
title: "劳累后感到气促或呼吸不畅", title: '劳累后感到气促或呼吸不畅',
}, },
{ {
id: "3", id: '3',
title: "静止时感到气促或呼吸不畅", title: '静止时感到气促或呼吸不畅',
}, },
{ {
id: "4", id: '4',
title: "依赖呼吸机", title: '依赖呼吸机',
}, },
], ],
}, },
{ {
title: "刷牙梳头能力受损", title: '刷牙梳头能力受损',
key: "BrushTeethAndCombHairScore", key: 'BrushTeethAndCombHairScore',
list: [ list: [
{ {
id: "1", id: '1',
title: "正常", title: '正常',
}, },
{ {
id: "2", id: '2',
title: "需要多费些力气但是不需要停下来", title: '需要多费些力气但是不需要停下来',
}, },
{ {
id: "3", id: '3',
title: "需要停下来休息才能完成", title: '需要停下来休息才能完成',
}, },
{ {
id: "4", id: '4',
title: "无法自己完成", title: '无法自己完成',
}, },
], ],
}, },
{ {
title: "从椅子上起身能力受损", title: '从椅子上起身能力受损',
key: "GetUpFromChairScore", key: 'GetUpFromChairScore',
list: [ list: [
{ {
id: "1", id: '1',
title: "正常", title: '正常',
}, },
{ {
id: "2", id: '2',
title: "轻度受损,有时需要用手帮忙", title: '轻度受损,有时需要用手帮忙',
}, },
{ {
id: "3", id: '3',
title: "中度受损,总是需要用手帮忙", title: '中度受损,总是需要用手帮忙',
}, },
{ {
id: "4", id: '4',
title: "严重受损,需要他人帮助", title: '严重受损,需要他人帮助',
}, },
], ],
}, },
{ {
title: "复视/重影", title: '复视/重影',
key: "DoubleVisionScore", key: 'DoubleVisionScore',
list: [ list: [
{ {
id: "1", id: '1',
title: "正常", title: '正常',
}, },
{ {
id: "2", id: '2',
title: "有,但不是每天", title: '有,但不是每天',
}, },
{ {
id: "3", id: '3',
title: "每天,但不是持续一整天", title: '每天,但不是持续一整天',
}, },
{ {
id: "4", id: '4',
title: "持续有", title: '持续有',
}, },
], ],
}, },
{ {
title: "眼睑下垂", title: '眼睑下垂',
key: "DroopyEyelidsScore", key: 'DroopyEyelidsScore',
list: [ list: [
{ {
id: "1", id: '1',
title: "正常", title: '正常',
}, },
{ {
id: "2", id: '2',
title: "有,但不是每天", title: '有,但不是每天',
}, },
{ {
id: "3", id: '3',
title: "每天,但不是持续一整天", title: '每天,但不是持续一整天',
}, },
{ {
id: "4", id: '4',
title: "持续有", title: '持续有',
}, },
], ],
}, },
@ -204,37 +205,37 @@ Component({
}, },
methods: { methods: {
drawImage1() { drawImage1() {
let self = this; const self = this
// destZoom: 10, // destZoom: 10,
this.drawImage1 = new Wxml2Canvas({ this.drawImage1 = new Wxml2Canvas({
obj: self, obj: self,
width: this.data.width, // 宽, 以iphone6为基准,传具体数值,其它机型自动适配 width: this.data.width, // 宽, 以iphone6为基准,传具体数值,其它机型自动适配
height: this.data.height, // 高 height: this.data.height, // 高
element: "canvas1", element: 'canvas1',
background: "#ffffff", background: '#ffffff',
progress(_percent) {}, progress(_percent) {},
finish(url) { finish(url) {
self.setData({ self.setData({
imgUrl: url, imgUrl: url,
}); })
self.triggerEvent("finish", url); self.triggerEvent('finish', url)
}, },
error(_res) {}, error(_res) {},
}); })
let data = { const data = {
list: [ list: [
{ {
type: "wxml", type: 'wxml',
class: "#canvas-bill-body-mp .draw_canvas", class: '#canvas-bill-body-mp .draw_canvas',
limit: "#canvas-bill-body-mp", limit: '#canvas-bill-body-mp',
x: 0, x: 0,
y: 0, y: 0,
}, },
], ],
}; }
this.drawImage1.draw(data); this.drawImage1.draw(data)
}, },
}, },
}); })

1966
src/components/customTable/wxml2canvas/index.js

File diff suppressed because it is too large Load Diff

216
src/components/ec-canvas/ec-canvas.js

@ -1,31 +1,32 @@
import WxCanvas from './wx-canvas'; import WxCanvas from './wx-canvas'
let ctx; let ctx
let echarts; let echarts
function compareVersion(v1, v2) { function compareVersion(v1, v2) {
v1 = v1.split('.'); v1 = v1.split('.')
v2 = v2.split('.'); v2 = v2.split('.')
const len = Math.max(v1.length, v2.length); const len = Math.max(v1.length, v2.length)
while (v1.length < len) { while (v1.length < len) {
v1.push('0'); v1.push('0')
} }
while (v2.length < len) { while (v2.length < len) {
v2.push('0'); v2.push('0')
} }
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
const num1 = parseInt(v1[i]); const num1 = Number.parseInt(v1[i])
const num2 = parseInt(v2[i]); const num2 = Number.parseInt(v2[i])
if (num1 > num2) { if (num1 > num2) {
return 1; return 1
} else if (num1 < num2) { }
return -1; else if (num1 < num2) {
return -1
} }
} }
return 0; return 0
} }
Component({ Component({
@ -49,223 +50,230 @@ Component({
isUseNewCanvas: false, isUseNewCanvas: false,
}, },
ready: async function () { async ready() {
echarts = await require.async('../../gift/compontnts/echart/echarts.js'); echarts = await require.async('../../gift/compontnts/echart/echarts.js')
// Disable prograssive because drawImage doesn't support DOM as parameter // Disable prograssive because drawImage doesn't support DOM as parameter
// See https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.drawImage.html // See https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.drawImage.html
echarts.registerPreprocessor((option) => { echarts.registerPreprocessor((option) => {
if (option && option.series) { if (option && option.series) {
if (option.series.length > 0) { if (option.series.length > 0) {
option.series.forEach((series) => { option.series.forEach((series) => {
series.progressive = 0; series.progressive = 0
}); })
} else if (typeof option.series === 'object') { }
option.series.progressive = 0; else if (typeof option.series === 'object') {
option.series.progressive = 0
} }
} }
}); })
if (!this.data.ec) { if (!this.data.ec) {
console.warn( console.warn(
'组件需绑定 ec 变量,例:<ec-canvas id="mychart-dom-bar" ' + '组件需绑定 ec 变量,例:<ec-canvas id="mychart-dom-bar" '
'canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>', + 'canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>',
); )
return; return
} }
if (!this.data.ec.lazyLoad) { if (!this.data.ec.lazyLoad) {
this.init(); this.init()
} }
}, },
methods: { methods: {
init: async function (callback) { async init(callback) {
echarts = await require.async('../../gift/compontnts/echart/echarts.js'); echarts = await require.async('../../gift/compontnts/echart/echarts.js')
const version = wx.getSystemInfoSync().SDKVersion; const version = wx.getSystemInfoSync().SDKVersion
const canUseNewCanvas = compareVersion(version, '2.9.0') >= 0; const canUseNewCanvas = compareVersion(version, '2.9.0') >= 0
const forceUseOldCanvas = this.data.forceUseOldCanvas; const forceUseOldCanvas = this.data.forceUseOldCanvas
const isUseNewCanvas = canUseNewCanvas && !forceUseOldCanvas; const isUseNewCanvas = canUseNewCanvas && !forceUseOldCanvas
this.setData({ isUseNewCanvas }); this.setData({ isUseNewCanvas })
if (forceUseOldCanvas && canUseNewCanvas) { if (forceUseOldCanvas && canUseNewCanvas) {
console.warn('开发者强制使用旧canvas,建议关闭'); console.warn('开发者强制使用旧canvas,建议关闭')
} }
if (isUseNewCanvas) { if (isUseNewCanvas) {
// console.log('微信基础库版本大于2.9.0,开始使用<canvas type="2d"/>'); // console.log('微信基础库版本大于2.9.0,开始使用<canvas type="2d"/>');
// 2.9.0 可以使用 <canvas type="2d"></canvas> // 2.9.0 可以使用 <canvas type="2d"></canvas>
this.initByNewWay(callback); this.initByNewWay(callback)
} else { }
const isValid = compareVersion(version, '1.9.91') >= 0; else {
const isValid = compareVersion(version, '1.9.91') >= 0
if (!isValid) { if (!isValid) {
console.error( console.error(
'微信基础库版本过低,需大于等于 1.9.91。' + '微信基础库版本过低,需大于等于 1.9.91。'
'参见:https://github.com/ecomfe/echarts-for-weixin' + + '参见:https://github.com/ecomfe/echarts-for-weixin'
'#%E5%BE%AE%E4%BF%A1%E7%89%88%E6%9C%AC%E8%A6%81%E6%B1%82', + '#%E5%BE%AE%E4%BF%A1%E7%89%88%E6%9C%AC%E8%A6%81%E6%B1%82',
); )
return; }
} else { else {
console.warn('建议将微信基础库调整大于等于2.9.0版本。升级后绘图将有更好性能'); console.warn('建议将微信基础库调整大于等于2.9.0版本。升级后绘图将有更好性能')
this.initByOldWay(callback); this.initByOldWay(callback)
} }
} }
}, },
initByOldWay(callback) { initByOldWay(callback) {
// 1.9.91 <= version < 2.9.0:原来的方式初始化 // 1.9.91 <= version < 2.9.0:原来的方式初始化
ctx = wx.createCanvasContext(this.data.canvasId, this); ctx = wx.createCanvasContext(this.data.canvasId, this)
const canvas = new WxCanvas(ctx, this.data.canvasId, false); const canvas = new WxCanvas(ctx, this.data.canvasId, false)
echarts.setCanvasCreator(() => { echarts.setCanvasCreator(() => {
return canvas; return canvas
}); })
// const canvasDpr = wx.getSystemInfoSync().pixelRatio // 微信旧的canvas不能传入dpr // const canvasDpr = wx.getSystemInfoSync().pixelRatio // 微信旧的canvas不能传入dpr
const canvasDpr = 1; const canvasDpr = 1
var query = wx.createSelectorQuery().in(this); const query = wx.createSelectorQuery().in(this)
query query
.select('.ec-canvas') .select('.ec-canvas')
.boundingClientRect((res) => { .boundingClientRect((res) => {
if (typeof callback === 'function') { if (typeof callback === 'function') {
this.chart = callback(canvas, res.width, res.height, canvasDpr); this.chart = callback(canvas, res.width, res.height, canvasDpr)
} else if (this.data.ec && typeof this.data.ec.onInit === 'function') { }
this.chart = this.data.ec.onInit(canvas, res.width, res.height, canvasDpr); else if (this.data.ec && typeof this.data.ec.onInit === 'function') {
} else { this.chart = this.data.ec.onInit(canvas, res.width, res.height, canvasDpr)
}
else {
this.triggerEvent('init', { this.triggerEvent('init', {
canvas: canvas, canvas,
width: res.width, width: res.width,
height: res.height, height: res.height,
canvasDpr: canvasDpr, // 增加了dpr,可方便外面echarts.init canvasDpr, // 增加了dpr,可方便外面echarts.init
}); })
} }
}) })
.exec(); .exec()
}, },
initByNewWay(callback) { initByNewWay(callback) {
// version >= 2.9.0:使用新的方式初始化 // version >= 2.9.0:使用新的方式初始化
const query = wx.createSelectorQuery().in(this); const query = wx.createSelectorQuery().in(this)
query query
.select('.ec-canvas') .select('.ec-canvas')
.fields({ node: true, size: true }) .fields({ node: true, size: true })
.exec((res) => { .exec((res) => {
const canvasNode = res[0].node; const canvasNode = res[0].node
this.canvasNode = canvasNode; this.canvasNode = canvasNode
const canvasDpr = wx.getSystemInfoSync().pixelRatio; const canvasDpr = wx.getSystemInfoSync().pixelRatio
const canvasWidth = res[0].width; const canvasWidth = res[0].width
const canvasHeight = res[0].height; const canvasHeight = res[0].height
const ctx = canvasNode.getContext('2d'); const ctx = canvasNode.getContext('2d')
const canvas = new WxCanvas(ctx, this.data.canvasId, true, canvasNode); const canvas = new WxCanvas(ctx, this.data.canvasId, true, canvasNode)
echarts.setCanvasCreator(() => { echarts.setCanvasCreator(() => {
return canvas; return canvas
}); })
if (typeof callback === 'function') { if (typeof callback === 'function') {
this.chart = callback(canvas, canvasWidth, canvasHeight, canvasDpr); this.chart = callback(canvas, canvasWidth, canvasHeight, canvasDpr)
} else if (this.data.ec && typeof this.data.ec.onInit === 'function') { }
this.chart = this.data.ec.onInit(canvas, canvasWidth, canvasHeight, canvasDpr); else if (this.data.ec && typeof this.data.ec.onInit === 'function') {
} else { this.chart = this.data.ec.onInit(canvas, canvasWidth, canvasHeight, canvasDpr)
}
else {
this.triggerEvent('init', { this.triggerEvent('init', {
canvas: canvas, canvas,
width: canvasWidth, width: canvasWidth,
height: canvasHeight, height: canvasHeight,
dpr: canvasDpr, dpr: canvasDpr,
}); })
} }
}); })
}, },
canvasToTempFilePath(opt) { canvasToTempFilePath(opt) {
if (this.data.isUseNewCanvas) { if (this.data.isUseNewCanvas) {
// 新版 // 新版
const query = wx.createSelectorQuery().in(this); const query = wx.createSelectorQuery().in(this)
query query
.select('.ec-canvas') .select('.ec-canvas')
.fields({ node: true, size: true }) .fields({ node: true, size: true })
.exec((res) => { .exec((res) => {
const canvasNode = res[0].node; const canvasNode = res[0].node
opt.canvas = canvasNode; opt.canvas = canvasNode
wx.canvasToTempFilePath(opt); wx.canvasToTempFilePath(opt)
}); })
} else { }
else {
// 旧的 // 旧的
if (!opt.canvasId) { if (!opt.canvasId) {
opt.canvasId = this.data.canvasId; opt.canvasId = this.data.canvasId
} }
ctx.draw(true, () => { ctx.draw(true, () => {
wx.canvasToTempFilePath(opt, this); wx.canvasToTempFilePath(opt, this)
}); })
} }
}, },
touchStart(e) { touchStart(e) {
if (this.chart && e.touches.length > 0) { if (this.chart && e.touches.length > 0) {
var touch = e.touches[0]; const touch = e.touches[0]
var handler = this.chart.getZr().handler; const handler = this.chart.getZr().handler
handler.dispatch('mousedown', { handler.dispatch('mousedown', {
zrX: touch.x, zrX: touch.x,
zrY: touch.y, zrY: touch.y,
preventDefault: () => {}, preventDefault: () => {},
stopImmediatePropagation: () => {}, stopImmediatePropagation: () => {},
stopPropagation: () => {}, stopPropagation: () => {},
}); })
handler.dispatch('mousemove', { handler.dispatch('mousemove', {
zrX: touch.x, zrX: touch.x,
zrY: touch.y, zrY: touch.y,
preventDefault: () => {}, preventDefault: () => {},
stopImmediatePropagation: () => {}, stopImmediatePropagation: () => {},
stopPropagation: () => {}, stopPropagation: () => {},
}); })
handler.processGesture(wrapTouch(e), 'start'); handler.processGesture(wrapTouch(e), 'start')
} }
}, },
touchMove(e) { touchMove(e) {
if (this.chart && e.touches.length > 0) { if (this.chart && e.touches.length > 0) {
var touch = e.touches[0]; const touch = e.touches[0]
var handler = this.chart.getZr().handler; const handler = this.chart.getZr().handler
handler.dispatch('mousemove', { handler.dispatch('mousemove', {
zrX: touch.x, zrX: touch.x,
zrY: touch.y, zrY: touch.y,
preventDefault: () => {}, preventDefault: () => {},
stopImmediatePropagation: () => {}, stopImmediatePropagation: () => {},
stopPropagation: () => {}, stopPropagation: () => {},
}); })
handler.processGesture(wrapTouch(e), 'change'); handler.processGesture(wrapTouch(e), 'change')
} }
}, },
touchEnd(e) { touchEnd(e) {
if (this.chart) { if (this.chart) {
const touch = e.changedTouches ? e.changedTouches[0] : {}; const touch = e.changedTouches ? e.changedTouches[0] : {}
var handler = this.chart.getZr().handler; const handler = this.chart.getZr().handler
handler.dispatch('mouseup', { handler.dispatch('mouseup', {
zrX: touch.x, zrX: touch.x,
zrY: touch.y, zrY: touch.y,
preventDefault: () => {}, preventDefault: () => {},
stopImmediatePropagation: () => {}, stopImmediatePropagation: () => {},
stopPropagation: () => {}, stopPropagation: () => {},
}); })
handler.dispatch('click', { handler.dispatch('click', {
zrX: touch.x, zrX: touch.x,
zrY: touch.y, zrY: touch.y,
preventDefault: () => {}, preventDefault: () => {},
stopImmediatePropagation: () => {}, stopImmediatePropagation: () => {},
stopPropagation: () => {}, stopPropagation: () => {},
}); })
handler.processGesture(wrapTouch(e), 'end'); handler.processGesture(wrapTouch(e), 'end')
} }
}, },
}, },
}); })
function wrapTouch(event) { function wrapTouch(event) {
for (let i = 0; i < event.touches.length; ++i) { for (let i = 0; i < event.touches.length; ++i) {
const touch = event.touches[i]; const touch = event.touches[i]
touch.offsetX = touch.x; touch.offsetX = touch.x
touch.offsetY = touch.y; touch.offsetY = touch.y
} }
return event; return event
} }

2
src/components/ec-canvas/ec-canvas.json

@ -1,4 +1,4 @@
{ {
"component": true, "component": true,
"usingComponents": {} "usingComponents": {}
} }

66
src/components/ec-canvas/wx-canvas.js

@ -1,24 +1,24 @@
export default class WxCanvas { export default class WxCanvas {
constructor(ctx, canvasId, isNew, canvasNode) { constructor(ctx, canvasId, isNew, canvasNode) {
this.ctx = ctx; this.ctx = ctx
this.canvasId = canvasId; this.canvasId = canvasId
this.chart = null; this.chart = null
this.isNew = isNew this.isNew = isNew
if (isNew) { if (isNew) {
this.canvasNode = canvasNode; this.canvasNode = canvasNode
} }
else { else {
this._initStyle(ctx); this._initStyle(ctx)
} }
// this._initCanvas(zrender, ctx); // this._initCanvas(zrender, ctx);
this._initEvent(); this._initEvent()
} }
getContext(contextType) { getContext(contextType) {
if (contextType === '2d') { if (contextType === '2d') {
return this.ctx; return this.ctx
} }
} }
@ -30,7 +30,7 @@ export default class WxCanvas {
// } // }
setChart(chart) { setChart(chart) {
this.chart = chart; this.chart = chart
} }
addEventListener() { addEventListener() {
@ -47,55 +47,58 @@ export default class WxCanvas {
_initCanvas(zrender, ctx) { _initCanvas(zrender, ctx) {
zrender.util.getContext = function () { zrender.util.getContext = function () {
return ctx; return ctx
}; }
zrender.util.$override('measureText', function (text, font) { zrender.util.$override('measureText', (text, font) => {
ctx.font = font || '12px sans-serif'; ctx.font = font || '12px sans-serif'
return ctx.measureText(text); return ctx.measureText(text)
}); })
} }
_initStyle(ctx) { _initStyle(ctx) {
ctx.createRadialGradient = () => { ctx.createRadialGradient = () => {
return ctx.createCircularGradient(arguments); return ctx.createCircularGradient(arguments)
}; }
} }
_initEvent() { _initEvent() {
this.event = {}; this.event = {}
const eventNames = [{ const eventNames = [{
wxName: 'touchStart', wxName: 'touchStart',
ecName: 'mousedown' ecName: 'mousedown',
}, { }, {
wxName: 'touchMove', wxName: 'touchMove',
ecName: 'mousemove' ecName: 'mousemove',
}, { }, {
wxName: 'touchEnd', wxName: 'touchEnd',
ecName: 'mouseup' ecName: 'mouseup',
}, { }, {
wxName: 'touchEnd', wxName: 'touchEnd',
ecName: 'click' ecName: 'click',
}]; }]
eventNames.forEach(name => { eventNames.forEach((name) => {
this.event[name.wxName] = e => { this.event[name.wxName] = (e) => {
const touch = e.touches[0]; const touch = e.touches[0]
this.chart.getZr().handler.dispatch(name.ecName, { this.chart.getZr().handler.dispatch(name.ecName, {
zrX: name.wxName === 'tap' ? touch.clientX : touch.x, zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
zrY: name.wxName === 'tap' ? touch.clientY : touch.y, zrY: name.wxName === 'tap' ? touch.clientY : touch.y,
preventDefault: () => {}, preventDefault: () => {},
stopImmediatePropagation: () => {}, stopImmediatePropagation: () => {},
stopPropagation: () => {} stopPropagation: () => {},
}); })
}; }
}); })
} }
set width(w) { set width(w) {
if (this.canvasNode) this.canvasNode.width = w if (this.canvasNode)
this.canvasNode.width = w
} }
set height(h) { set height(h) {
if (this.canvasNode) this.canvasNode.height = h if (this.canvasNode)
this.canvasNode.height = h
} }
get width() { get width() {
@ -103,6 +106,7 @@ export default class WxCanvas {
return this.canvasNode.width return this.canvasNode.width
return 0 return 0
} }
get height() { get height() {
if (this.canvasNode) if (this.canvasNode)
return this.canvasNode.height return this.canvasNode.height

149
src/components/freeAudio/index.js

@ -1,5 +1,4 @@
const app = getApp(); const app = getApp()
import dayjs from "dayjs";
Component({ Component({
behaviors: [], behaviors: [],
properties: { properties: {
@ -7,19 +6,19 @@ Component({
type: Object, type: Object,
observer(val) { observer(val) {
if (this.audioContext) { if (this.audioContext) {
const { play } = this.data; const { play } = this.data
if (play) { if (play) {
this.audioContext.pause(); this.audioContext.pause()
this.setData({ this.setData({
play: false, play: false,
progress: 0, progress: 0,
time: "00", time: '00',
}); })
} }
this.audioContext.destroy(); this.audioContext.destroy()
} }
if (val) { if (val) {
this.audioAddEventListener(val); this.audioAddEventListener(val)
} }
}, },
}, },
@ -27,8 +26,8 @@ Component({
data: { data: {
Timestamp: app.globalData.Timestamp, Timestamp: app.globalData.Timestamp,
progress: 0, progress: 0,
time: "00", time: '00',
duration: "00", duration: '00',
play: false, play: false,
loading: true, loading: true,
@ -41,136 +40,138 @@ Component({
moved() {}, moved() {},
detached() { detached() {
if (this.audioContext) { if (this.audioContext) {
const { play } = this.data; const { play } = this.data
if (play) { if (play) {
this.audioContext.pause(); this.audioContext.pause()
} }
this.audioContext.destroy(); this.audioContext.destroy()
} }
this.audioAddEventListener = null; this.audioAddEventListener = null
this.setData({ this.setData({
play: false, play: false,
progress: 0, progress: 0,
time: "00", time: '00',
}); })
}, },
}, },
pageLifetimes: { pageLifetimes: {
// 组件所在页面的生命周期函数 // 组件所在页面的生命周期函数
show: function () {}, show() {},
hide: function () { hide() {
const { play } = this.data; const { play } = this.data
if (play) { if (play) {
this.audioContext.pause(); this.audioContext.pause()
} }
}, },
resize: function () {}, resize() {},
}, },
methods: { methods: {
togglePlay() { togglePlay() {
const { play, loading } = this.data; const { play, loading } = this.data
if (loading) { if (loading) {
wx.showToast({ wx.showToast({
title: "音频加载中", title: '音频加载中',
icon: "none", icon: 'none',
}); })
return; return
} }
if (play) { if (play) {
this.audioContext.pause(); this.audioContext.pause()
} else { }
this.audioContext.play(); else {
this.audioContext.play()
} }
}, },
formatTime(time) { formatTime(time) {
let m = parseInt(time / 60); const m = Number.parseInt(time / 60)
let s = parseInt(time % 60); const s = Number.parseInt(time % 60)
return this.towNum(m) + ":" + this.towNum(s); return `${this.towNum(m)}:${this.towNum(s)}`
}, },
towNum(num) { towNum(num) {
if (num >= 10) { if (num >= 10) {
return num; return num
} else { }
return "0" + num; else {
return `0${num}`
} }
}, },
audioAddEventListener(val) { audioAddEventListener(val) {
const that = this; const that = this
this.setData({ this.setData({
duration: this.formatTime(val.size), duration: this.formatTime(val.size),
}); })
that.audioContext = wx.createInnerAudioContext(); that.audioContext = wx.createInnerAudioContext()
that.audioContext.src = val.url; that.audioContext.src = val.url
that.setData({ that.setData({
loading: false, loading: false,
}); })
that.audioContext.onError(({ errCode, ...reset }) => { that.audioContext.onError(({ errCode, ...reset }) => {
console.log("reset: ", reset); console.log('reset: ', reset)
console.log("errCode: ", errCode); console.log('errCode: ', errCode)
if (errCode === 10004 || errCode == 10001 || errCode == -1) { if (errCode === 10004 || errCode == 10001 || errCode == -1) {
that.audioContext.destroy(); that.audioContext.destroy()
that.setData({ that.setData({
loading: true, loading: true,
}); })
setTimeout(() => { setTimeout(() => {
that.audioAddEventListener(val); that.audioAddEventListener(val)
}, 300); }, 300)
} }
}); })
that.audioContext.onPlay(() => { that.audioContext.onPlay(() => {
that.setData({ that.setData({
play: true, play: true,
}); })
}); })
that.audioContext.onPause(() => { that.audioContext.onPause(() => {
console.log(1111111); console.log(1111111)
that.setData({ that.setData({
play: false, play: false,
}); })
}); })
that.audioContext.onEnded(() => { that.audioContext.onEnded(() => {
that.audioContext.seek(0); that.audioContext.seek(0)
that.setData({ that.setData({
play: false, play: false,
progress: 0, progress: 0,
time: "00", time: '00',
}); })
}); })
that.audioContext.onTimeUpdate(() => { that.audioContext.onTimeUpdate(() => {
const duration = that.audioContext.duration || 0; const duration = that.audioContext.duration || 0
const currentTime = that.audioContext.currentTime || 0; const currentTime = that.audioContext.currentTime || 0
const progress = (currentTime / duration) * 100; const progress = (currentTime / duration) * 100
if (duration == Infinity) { if (duration == Infinity) {
return; return
} }
that.setData({ that.setData({
play: true, play: true,
duration: that.formatTime(duration), duration: that.formatTime(duration),
time: that.formatTime(currentTime), time: that.formatTime(currentTime),
}); })
if (that.data.progressimg) { if (that.data.progressimg) {
this.setData({ this.setData({
progress: progress, progress,
}); })
} }
}); })
}, },
handleAuthChangeimg() { handleAuthChangeimg() {
console.log(11111); console.log(11111)
this.setData({ this.setData({
progressimg: false, progressimg: false,
}); })
}, },
handleAuthChange(e) { handleAuthChange(e) {
console.log(22222222222); console.log(22222222222)
let { duration } = this.data; const { duration } = this.data
const secods = this.audioContext.duration || duration.split(":")[0] * 60 + duration.split(":")[1] * 1; const secods = this.audioContext.duration || duration.split(':')[0] * 60 + duration.split(':')[1] * 1
const progress = e.detail.value; const progress = e.detail.value
let seek = ((secods / 100) * progress).toFixed(3) * 1; const seek = ((secods / 100) * progress).toFixed(3) * 1
this.audioContext.seek(seek); this.audioContext.seek(seek)
this.setData({ this.setData({
progressimg: true, progressimg: true,
}); })
}, },
}, },
}); })

2
src/components/image-merge/index.json

@ -5,4 +5,4 @@
"van-icon": "@vant/weapp/icon/index", "van-icon": "@vant/weapp/icon/index",
"van-toast": "@vant/weapp/toast/index" "van-toast": "@vant/weapp/toast/index"
} }
} }

6
src/components/loginNavbar/index.ts

@ -1,4 +1,4 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
Component({ Component({
properties: { properties: {
@ -17,7 +17,7 @@ Component({
}, },
methods: { methods: {
handleBack() { handleBack() {
this.triggerEvent("back"); this.triggerEvent('back')
}, },
}, },
}); })

6
src/components/navbar/index.ts

@ -32,7 +32,7 @@ Component({
*/ */
data: { data: {
imageUrl: app.globalData.imageUrl, imageUrl: app.globalData.imageUrl,
Timestamp:app.globalData.Timestamp Timestamp: app.globalData.Timestamp,
}, },
/** /**
@ -40,8 +40,8 @@ Component({
*/ */
methods: { methods: {
onClickLeft() { onClickLeft() {
if(this.data.back) if (this.data.back)
this.triggerEvent('clickLeft', {}, {}) this.triggerEvent('clickLeft', {}, {})
}, },
onClickRight() { onClickRight() {
this.triggerEvent('clickRight', {}, {}) this.triggerEvent('clickRight', {}, {})

5
src/components/noteImagePreview/index.json

@ -1,6 +1,7 @@
{ {
"component": true, "component": true,
"usingComponents": { "usingComponents": {
"van-icon": "@vant/weapp/icon/index" "van-icon": "@vant/weapp/icon/index",
"navbar": "/components/navbar/index"
} }
} }

3
src/components/noteImagePreview/index.ts

@ -16,6 +16,7 @@ Component({
data: { data: {
visible: false, visible: false,
src: '', src: '',
navHeight: wx.getSystemInfoSync().statusBarHeight + 44,
}, },
methods: { methods: {
@ -50,6 +51,8 @@ Component({
wx.showModal({ wx.showModal({
title: '提示', title: '提示',
content: '确定要删除这张照片吗?', content: '确定要删除这张照片吗?',
confirmColor: '#8c75d0',
cancelColor: '#141515',
success: (res) => { success: (res) => {
if (res.confirm) { if (res.confirm) {
this.handleHidePreview() this.handleHidePreview()

8
src/components/noteImagePreview/index.wxml

@ -1,10 +1,12 @@
<view class="preview-container {{visible ? 'show' : ''}}"> <view class="preview-container {{visible ? 'show' : ''}}">
<!-- 图片展示区域 --> <navbar fixed title="" custom-style="background:transparent" bind:click-left="handleBack">
<view class="image-wrapper"> <van-icon name="arrow-left" slot="left" size="18px" color="#fff" bind:tap="handleBack" />
</navbar>
<view class="image-wrapper" style="padding-top:{{navHeight}}px;">
<image class="preview-image" src="{{src}}" mode="aspectFit" /> <image class="preview-image" src="{{src}}" mode="aspectFit" />
</view> </view>
<!-- 底部操作栏 -->
<view class="action-bar"> <view class="action-bar">
<view class="btn btn-delete" bindtap="handleDelete">删除</view> <view class="btn btn-delete" bindtap="handleDelete">删除</view>
<view class="btn btn-retake" bindtap="handleRetake">重拍</view> <view class="btn btn-retake" bindtap="handleRetake">重拍</view>

6
src/components/pageNavbar/index.ts

@ -1,4 +1,4 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
Component({ Component({
properties: { properties: {
@ -17,7 +17,7 @@ Component({
}, },
methods: { methods: {
handleBack() { handleBack() {
wx.navigateBack(); wx.navigateBack()
}, },
}, },
}); })

10
src/components/pickerArea/index.scss

@ -41,7 +41,7 @@
padding: 18rpx 30rpx; padding: 18rpx 30rpx;
box-shadow: 0rpx 4rpx 12rpx 0rpx rgba(0, 0, 0, 0.11); box-shadow: 0rpx 4rpx 12rpx 0rpx rgba(0, 0, 0, 0.11);
border-radius: 12rpx 12rpx 12rpx 12rpx; border-radius: 12rpx 12rpx 12rpx 12rpx;
border: 2rpx solid #B982FF; border: 2rpx solid #b982ff;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
@ -69,7 +69,7 @@
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
background: linear-gradient( 197deg, #FFBCF9 0%, #B982FF 100%); background: linear-gradient(197deg, #ffbcf9 0%, #b982ff 100%);
border-radius: 12rpx 12rpx 12rpx 12rpx; border-radius: 12rpx 12rpx 12rpx 12rpx;
} }
} }
@ -91,7 +91,7 @@
background: #f7f8f9; background: #f7f8f9;
&.active { &.active {
color: #fff; color: #fff;
background-color: #B982FF; background-color: #b982ff;
} }
} }
} }
@ -118,9 +118,9 @@
height: 36rpx; height: 36rpx;
} }
&.active { &.active {
color: #B982FF; color: #b982ff;
.word { .word {
color: #B982FF; color: #b982ff;
} }
} }
} }

52
src/components/popup/index.scss

@ -648,6 +648,58 @@
} }
} }
.popup18 {
.badge {
position: relative;
z-index: 1;
display: block;
width: 144rpx;
height: 144rpx;
margin: 0 auto -72rpx;
text-align: center;
}
.popup-container {
width: 670rpx;
box-sizing: border-box;
padding: 118rpx 48rpx 44rpx;
border-radius: 32rpx;
background: #fff;
.title {
font-size: 40rpx;
color: #211d2e;
font-weight: bold;
text-align: center;
}
.p-footer {
margin-top: 52rpx;
display: flex;
gap: 30rpx;
.sure,
.cancel {
flex: 1;
font-size: 36rpx;
border-radius: 100rpx;
height: 88rpx;
box-sizing: border-box;
}
.cancel {
color: #b982ff;
border: 1px solid #b982ff;
display: flex;
align-items: center;
justify-content: center;
}
.sure {
padding: 0;
background: linear-gradient(344deg, #ffbcf9 0%, #b982ff 100%);
color: #ffffff;
display: flex;
align-items: center;
justify-content: center;
}
}
}
}
.close { .close {
margin: 48rpx auto 0; margin: 48rpx auto 0;

14
src/components/popup/index.wxml

@ -209,7 +209,7 @@
<view class="title">确认删除记录?</view> <view class="title">确认删除记录?</view>
<view class="content"> <view class="content">
删除 删除
<text class="date">2026-04-02</text> <text class="date">{{params.recordDate}}</text>
记录 记录
<view>此操作不可逆,相关照片将永久删除</view> <view>此操作不可逆,相关照片将永久删除</view>
</view> </view>
@ -241,6 +241,18 @@
</view> </view>
</view> </view>
</view> </view>
<view class="popup18" wx:if="{{type==='popup18'}}">
<image class="badge" src="{{imageUrl}}icon156.png?t={{Timestamp}}"></image>
<view class="popup-container">
<view class="title">
是否替换已有基准照
</view>
<view class="p-footer">
<view class="cancel" bind:tap="handleCancel">取消</view>
<view class="sure" bind:tap="handleOk">确认替换</view>
</view>
</view>
</view>
<image <image
wx:if="{{params.close}}" wx:if="{{params.close}}"

209
src/components/star/index.ts

@ -1,70 +1,70 @@
const app = getApp(); const app = getApp()
/** /**
* >=min && <=max * >=min && <=max
* @param min * @param min
* @param max * @param max
*/ */
function getRandom(min, max) { function getRandom(min, max) {
return min + Math.floor(Math.random() * (max - min + 1)); return min + Math.floor(Math.random() * (max - min + 1))
} }
Component({ Component({
options: {}, options: {},
lifetimes: { lifetimes: {
attached() { attached() {
const query = wx.createSelectorQuery().in(this); const query = wx.createSelectorQuery().in(this)
query query
.select("#thumsCanvas") .select('#thumsCanvas')
.fields({ node: true, size: true }) .fields({ node: true, size: true })
.exec((res) => { .exec((res) => {
const canvas = res[0].node; const canvas = res[0].node
const context = canvas.getContext("2d"); const context = canvas.getContext('2d')
this.setData({ this.setData({
context: context, context,
}); })
const dpr = wx.getSystemInfoSync().pixelRatio; const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr; canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr; canvas.height = res[0].height * dpr
this.data.width = res[0].width * dpr; this.data.width = res[0].width * dpr
this.data.height = res[0].height * dpr; this.data.height = res[0].height * dpr
// context.fillStyle = "rgba(255, 255, 255, 0)"; // context.fillStyle = "rgba(255, 255, 255, 0)";
const images = [ const images = [
"za-images/star/icon1.png", 'za-images/star/icon1.png',
"za-images/star/icon2.png", 'za-images/star/icon2.png',
"za-images/star/icon3.png", 'za-images/star/icon3.png',
"za-images/star/icon4.png", 'za-images/star/icon4.png',
"za-images/star/icon5.png", 'za-images/star/icon5.png',
"za-images/star/icon6.png", 'za-images/star/icon6.png',
"za-images/star/icon7.png", 'za-images/star/icon7.png',
"za-images/star/icon8.png", 'za-images/star/icon8.png',
]; ]
const promiseAll = [] as Array<Promise<any>>; const promiseAll = [] as Array<Promise<any>>
images.forEach((src) => { images.forEach((src) => {
const p = new Promise(function (resolve) { const p = new Promise((resolve) => {
const img = canvas.createImage(); const img = canvas.createImage()
img.onerror = img.onload = resolve.bind(null, img); img.onerror = img.onload = resolve.bind(null, img)
img.src = app.globalData.imageUrl + src; img.src = app.globalData.imageUrl + src
}); })
promiseAll.push(p); promiseAll.push(p)
}); })
Promise.all(promiseAll).then((imgsList) => { Promise.all(promiseAll).then((imgsList) => {
const imgsLists = imgsList.filter((d) => { const imgsLists = imgsList.filter((d) => {
if (d && d.width > 0) return true; if (d && d.width > 0)
return false; return true
}); return false
})
this.setData({ this.setData({
imgsList: imgsLists, imgsList: imgsLists,
}); })
if (this.data.imgsList.length == 0) { if (this.data.imgsList.length == 0) {
// logger.error("imgsList load all error"); // logger.error("imgsList load all error");
wx.showToast({ wx.showToast({
icon: "none", icon: 'none',
title: "imgsList load all error", title: 'imgsList load all error',
}); })
return;
} }
}); })
}); })
}, },
}, },
properties: {}, properties: {},
@ -79,98 +79,105 @@ Component({
}, },
methods: { methods: {
handleTap() { handleTap() {
this.start(); this.start()
}, },
createRender() { createRender() {
if (this.data.imgsList.length == 0) return null; if (this.data.imgsList.length == 0)
const basicScale = [0.6, 0.9, 1.2][getRandom(0, 2)]; return null
const basicScale = [0.6, 0.9, 1.2][getRandom(0, 2)]
const getScale = (diffTime) => { const getScale = (diffTime) => {
if (diffTime < this.data.scaleTime) { if (diffTime < this.data.scaleTime) {
return +(diffTime / this.data.scaleTime).toFixed(2) * basicScale; return +(diffTime / this.data.scaleTime).toFixed(2) * basicScale
} else {
return basicScale;
} }
}; else {
const context = this.data.context; return basicScale
}
}
const context = this.data.context
// 随机读取一个图片来渲染 // 随机读取一个图片来渲染
const image: any = this.data.imgsList[getRandom(0, this.data.imgsList.length - 1)]; const image: any = this.data.imgsList[getRandom(0, this.data.imgsList.length - 1)]
const offset = 20; const offset = 20
const basicX = this.data.width / 2 + getRandom(-offset, offset); const basicX = this.data.width / 2 + getRandom(-offset, offset)
const angle = getRandom(2, 10); const angle = getRandom(2, 10)
let ratio = getRandom(10, 30) * (getRandom(0, 1) ? 1 : -1); const ratio = getRandom(10, 30) * (getRandom(0, 1) ? 1 : -1)
const getTranslateX = (diffTime) => { const getTranslateX = (diffTime) => {
if (diffTime < this.data.scaleTime) { if (diffTime < this.data.scaleTime) {
// 放大期间,不进行摇摆位移 // 放大期间,不进行摇摆位移
return basicX; return basicX
} else { }
return basicX + ratio * Math.sin(angle * (diffTime - this.data.scaleTime)); else {
return basicX + ratio * Math.sin(angle * (diffTime - this.data.scaleTime))
} }
}; }
const getTranslateY = (diffTime) => { const getTranslateY = (diffTime) => {
return image.height / 2 + (this.data.height - image.height / 2) * (1 - diffTime); return image.height / 2 + (this.data.height - image.height / 2) * (1 - diffTime)
}; }
const fadeOutStage = getRandom(14, 18) / 100; const fadeOutStage = getRandom(14, 18) / 100
const getAlpha = (diffTime) => { const getAlpha = (diffTime) => {
let left = 1 - +diffTime; const left = 1 - +diffTime
if (left > fadeOutStage) { if (left > fadeOutStage) {
return 1; return 1
} else {
return 1 - +((fadeOutStage - left) / fadeOutStage).toFixed(2);
} }
}; else {
return 1 - +((fadeOutStage - left) / fadeOutStage).toFixed(2)
}
}
return (diffTime) => { return (diffTime) => {
// 差值满了,即结束了 0 ---》 1 // 差值满了,即结束了 0 ---》 1
if (diffTime >= 1) return true; if (diffTime >= 1)
context.save(); return true
const scale = getScale(diffTime); context.save()
const scale = getScale(diffTime)
// const rotate = getRotate(); // const rotate = getRotate();
const translateX = getTranslateX(diffTime); const translateX = getTranslateX(diffTime)
const translateY = getTranslateY(diffTime); const translateY = getTranslateY(diffTime)
context.translate(translateX, translateY); context.translate(translateX, translateY)
context.scale(scale, scale); context.scale(scale, scale)
// context.rotate(rotate * Math.PI / 180); // context.rotate(rotate * Math.PI / 180);
context.globalAlpha = getAlpha(diffTime); context.globalAlpha = getAlpha(diffTime)
context.drawImage(image, -image.width / 2, -image.height / 2, image.width, image.height); context.drawImage(image, -image.width / 2, -image.height / 2, image.width, image.height)
context.restore(); context.restore()
}; }
}, },
scan() { scan() {
this.data.context.clearRect(0, 0, this.data.width, this.data.height); this.data.context.clearRect(0, 0, this.data.width, this.data.height)
this.data.context.fillStyle = "rgba(255, 255, 255, 0)"; this.data.context.fillStyle = 'rgba(255, 255, 255, 0)'
this.data.context.fillRect(0, 0, 200, 400); this.data.context.fillRect(0, 0, 200, 400)
let index = 0; let index = 0
let length = this.data.renderList.length; let length = this.data.renderList.length
if (length > 0) { if (length > 0) {
this.requestFrame(this.scan.bind(this)); this.requestFrame(this.scan.bind(this))
this.setData({ this.setData({
scanning: true, scanning: true,
}); })
} else { }
else {
this.setData({ this.setData({
scanning: false, scanning: false,
}); })
} }
while (index < length) { while (index < length) {
const child = this.data.renderList[index]; const child = this.data.renderList[index]
if (!child || !child.render || child.render.call(null, (Date.now() - child.timestamp) / child.duration)) { if (!child || !child.render || child.render.call(null, (Date.now() - child.timestamp) / child.duration)) {
// 结束了,删除该动画 // 结束了,删除该动画
this.setData({ this.setData({
renderList: [...this.data.renderList].filter((_item, fIndex) => fIndex != index), renderList: [...this.data.renderList].filter((_item, fIndex) => fIndex != index),
}); })
length--; length--
} else { }
else {
// continue // continue
index++; index++
} }
} }
}, },
start() { start() {
const render = this.createRender(); const render = this.createRender()
const duration = getRandom(1500, 3000); const duration = getRandom(1500, 3000)
this.setData({ this.setData({
renderList: [ renderList: [
...this.data.renderList, ...this.data.renderList,
@ -180,25 +187,25 @@ Component({
timestamp: Date.now(), timestamp: Date.now(),
}, },
], ],
}); })
if (!this.data.scanning) { if (!this.data.scanning) {
this.setData({ this.setData({
scanning: true, scanning: true,
}); })
this.requestFrame(this.scan.bind(this)); this.requestFrame(this.scan.bind(this))
// this.scan.bind(this)(); // this.scan.bind(this)();
} }
return this; return this
}, },
requestFrame(cb) { requestFrame(cb) {
return ( return (
this.data.context.requestAnimationFrame || this.data.context.requestAnimationFrame
(function (callback) { || (function (callback) {
setTimeout(callback, 1000 / 60); setTimeout(callback, 1000 / 60)
})(cb) })(cb)
); )
}, },
}, },
}); })

8
src/components/text-expandsion/index.scss

@ -10,13 +10,13 @@
max-height: 9em; max-height: 9em;
text-align: justify; text-align: justify;
&::before { &::before {
content: ""; content: '';
float: right; float: right;
height: 100%; height: 100%;
margin-bottom: -40rpx; margin-bottom: -40rpx;
} }
&::after { &::after {
content: ""; content: '';
width: 100vw; width: 100vw;
height: 100vh; height: 100vh;
position: absolute; position: absolute;
@ -32,11 +32,11 @@
clear: both; clear: both;
line-height: 42rpx; line-height: 42rpx;
&::before { &::before {
content: "..."; content: '...';
margin-right: 8rpx; margin-right: 8rpx;
} }
&::after { &::after {
content: ""; content: '';
display: inline-block; display: inline-block;
margin-bottom: 2rpx; margin-bottom: 2rpx;
margin-left: 4rpx; margin-left: 4rpx;

50
src/components/timeOut/index.ts

@ -1,4 +1,4 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
// pages/story/a.ts // pages/story/a.ts
Component({ Component({
@ -8,7 +8,7 @@ Component({
properties: { properties: {
detailId: { detailId: {
type: String, type: String,
value: "0", value: '0',
}, },
asideOut: { asideOut: {
type: Boolean, type: Boolean,
@ -16,7 +16,7 @@ Component({
}, },
asideType: { asideType: {
type: String, type: String,
value: "", value: '',
}, },
timeToast: { timeToast: {
type: Boolean, type: Boolean,
@ -24,33 +24,34 @@ Component({
}, },
timeToastType: { timeToastType: {
type: String, type: String,
value: "", value: '',
}, },
timeToastParams: { timeToastParams: {
type: Object, type: Object,
value() { value() {
return {}; return {}
}, },
}, },
}, },
observers: { observers: {
asideOut: function (asideOut) { asideOut(asideOut) {
if (asideOut) { if (asideOut) {
setTimeout(() => { setTimeout(() => {
this.countDown(); this.countDown()
}, 1000); }, 1000)
} }
}, },
}, },
lifetimes: { lifetimes: {
attached() { attached() {
let systemInfo = wx.getSystemInfoSync(); const systemInfo = wx.getSystemInfoSync()
this.setData({ this.setData({
sliderTop: systemInfo.screenHeight - 250, sliderTop: systemInfo.screenHeight - 250,
}); })
}, },
detached() { detached() {
if (this.timer) clearInterval(this.timer); if (this.timer)
clearInterval(this.timer)
}, },
}, },
data: { data: {
@ -66,25 +67,26 @@ Component({
methods: { methods: {
timer: null as any, timer: null as any,
countDown() { countDown() {
const that = this; const that = this
if (that.timer) return; if (that.timer)
let circle = 100; return
let circle = 100
that.timer = setInterval(() => { that.timer = setInterval(() => {
circle--; circle--
that.setData({ that.setData({
circleVal: circle, circleVal: circle,
centerVal: Math.floor(circle / 10), centerVal: Math.floor(circle / 10),
}); })
if (circle <= 0) { if (circle <= 0) {
clearInterval(that.timer); clearInterval(that.timer)
this.handleAsideOut(); this.handleAsideOut()
} }
}, 100); }, 100)
}, },
handleAsideOut() { handleAsideOut() {
wx.ajax({ wx.ajax({
method: "POST", method: 'POST',
url: "?r=xd/score/send-score", url: '?r=xd/score/send-score',
data: { data: {
Type: this.data.asideType, Type: this.data.asideType,
Id: this.data.detailId, Id: this.data.detailId,
@ -93,9 +95,9 @@ Component({
if (!Array.isArray(res)) { if (!Array.isArray(res)) {
this.setData({ this.setData({
rewardScore: res.rewardScore, rewardScore: res.rewardScore,
}); })
} }
}); })
}, },
}, },
}); })

72
src/components/toast/index.ts

@ -1,4 +1,4 @@
const app = getApp(); const app = getApp()
Component({ Component({
properties: { properties: {
show: { show: {
@ -9,7 +9,7 @@ Component({
params: { params: {
type: Object, type: Object,
value() { value() {
return {}; return {}
}, },
}, },
}, },
@ -19,37 +19,37 @@ Component({
app.zdGetTheme().then((res) => { app.zdGetTheme().then((res) => {
this.setData({ this.setData({
theme: res, theme: res,
}); })
}); })
if (this.data.params.timeOut) { if (this.data.params.timeOut) {
let time = this.data.params.timeOut; let time = this.data.params.timeOut
const timerFunc = () => { const timerFunc = () => {
if (time <= 0) { if (time <= 0) {
this.setData({ this.setData({
timeOut: '', timeOut: '',
}); })
clearInterval(this.timer); clearInterval(this.timer)
return; return
} }
this.setData({ this.setData({
timeOut: `${time}s`, timeOut: `${time}s`,
}); })
--time; --time
}; }
timerFunc(); timerFunc()
this.timer = setInterval(timerFunc, 1000); this.timer = setInterval(timerFunc, 1000)
} }
if (['storyLead', 'storyStar', 'storyShare'].includes(this.data.type)) { if (['storyLead', 'storyStar', 'storyShare'].includes(this.data.type)) {
this.getSettingInfo(); this.getSettingInfo()
} }
} }
this.setData({ this.setData({
zdUserInfo: app.globalData.zdUserInfo, zdUserInfo: app.globalData.zdUserInfo,
}); })
}, },
type(val) { type(val) {
if (val === 'healthCare') { if (val === 'healthCare') {
this.getOpenPatientList(); this.getOpenPatientList()
} }
}, },
}, },
@ -66,42 +66,42 @@ Component({
this.setData({ this.setData({
imageUrl: app.globalData.imageUrl, imageUrl: app.globalData.imageUrl,
Timestamp: app.globalData.Timestamp, Timestamp: app.globalData.Timestamp,
}); })
}, },
}, },
methods: { methods: {
timer: null as any, timer: null as any,
handleOk() { handleOk() {
if (this.data.timeOut) { if (this.data.timeOut) {
return; return
} }
this.triggerEvent('ok', { protocol: this.data.protocol }); this.triggerEvent('ok', { protocol: this.data.protocol })
}, },
handleCancel(e = { currentTarget: { dataset: { key: '' } } }) { handleCancel(e = { currentTarget: { dataset: { key: '' } } }) {
const { key } = e.currentTarget.dataset; const { key } = e.currentTarget.dataset
if (this.timer) { if (this.timer) {
clearInterval(this.timer); clearInterval(this.timer)
this.setData({ this.setData({
timeOut: '', timeOut: '',
}); })
} }
this.triggerEvent('cancel', { key }); this.triggerEvent('cancel', { key })
}, },
handleTaskCancel() { handleTaskCancel() {
this.triggerEvent('taskCancel'); this.triggerEvent('taskCancel')
}, },
handleJump() { handleJump() {
this.triggerEvent('jump'); this.triggerEvent('jump')
}, },
handleDel() { handleDel() {
this.triggerEvent('del'); this.triggerEvent('del')
}, },
routerTo(e) { routerTo(e) {
const { path } = e.currentTarget.dataset; const { path } = e.currentTarget.dataset
wx.navigateTo({ wx.navigateTo({
url: path, url: path,
}); })
this.handleCancel(); this.handleCancel()
}, },
getSettingInfo() { getSettingInfo() {
wx.ajax({ wx.ajax({
@ -111,8 +111,8 @@ Component({
}).then((res) => { }).then((res) => {
this.setData({ this.setData({
settingsInfo: res, settingsInfo: res,
}); })
}); })
}, },
getOpenPatientList() { getOpenPatientList() {
wx.ajax({ wx.ajax({
@ -122,18 +122,18 @@ Component({
}).then((res) => { }).then((res) => {
this.setData({ this.setData({
openPatientList: res, openPatientList: res,
}); })
}); })
}, },
handleProtocolChange() { handleProtocolChange() {
this.setData({ this.setData({
protocol: !this.data.protocol, protocol: !this.data.protocol,
}); })
}, },
handleAdlQuestion() { handleAdlQuestion() {
wx.navigateTo({ wx.navigateTo({
url: '/pages/repositoryDetail/index?id=9', url: '/pages/repositoryDetail/index?id=9',
}); })
}, },
}, },
}); })

87
src/components/uploadFile/index.ts

@ -1,4 +1,4 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
// pages/story/a.ts // pages/story/a.ts
Component({ Component({
@ -32,17 +32,17 @@ Component({
*/ */
methods: { methods: {
GetExtensionFileName(pathfilename) { GetExtensionFileName(pathfilename) {
const reg = /(\\+)/g; const reg = /(\\+)/g
const pString = pathfilename.replace(reg, '#'); //用正则表达式来将\或\\替换成# const pString = pathfilename.replace(reg, '#') // 用正则表达式来将\或\\替换成#
const arr = pString.split('#'); // 以“#”为分隔符,将字符分解为数组 例如 D Program Files bg.png const arr = pString.split('#') // 以“#”为分隔符,将字符分解为数组 例如 D Program Files bg.png
const lastString = arr[arr.length - 1]; //取最后一个字符 const lastString = arr[arr.length - 1] // 取最后一个字符
const arr2 = lastString.split('.'); // 再以"."作为分隔符 const arr2 = lastString.split('.') // 再以"."作为分隔符
return arr2[arr2.length - 1]; //将后缀名返回出来 return arr2[arr2.length - 1] // 将后缀名返回出来
}, },
handleAfterRead(e) { handleAfterRead(e) {
this.uploadFile(e.detail.file).then((res) => { this.uploadFile(e.detail.file).then((res) => {
this.triggerEvent('file', res as object); this.triggerEvent('file', res as object)
}); })
}, },
handleChooseAvatar(e) { handleChooseAvatar(e) {
this.uploadFile({ this.uploadFile({
@ -50,8 +50,8 @@ Component({
tempFilePath: e.detail.avatarUrl, tempFilePath: e.detail.avatarUrl,
size: 0, size: 0,
}).then((res) => { }).then((res) => {
this.triggerEvent('file', res as object); this.triggerEvent('file', res as object)
}); })
}, },
handleChooseFile() { handleChooseFile() {
wx.chooseMessageFile({ wx.chooseMessageFile({
@ -63,41 +63,44 @@ Component({
fileType: res.tempFiles[0].type, fileType: res.tempFiles[0].type,
tempFilePath: res.tempFiles[0].path, tempFilePath: res.tempFiles[0].path,
}).then((res) => { }).then((res) => {
this.triggerEvent('file', res as object); this.triggerEvent('file', res as object)
}); })
}, },
fail() { fail() {
wx.showToast({ wx.showToast({
icon: 'none', icon: 'none',
title: '取消选择', title: '取消选择',
}); })
}, },
}); })
}, },
uploadFile(item) { uploadFile(item) {
wx.showLoading({ wx.showLoading({
title: '正在上传', title: '正在上传',
}); })
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let url = `${app.globalData.upFileUrl}?r=file-service/upload-`; let url = `${app.globalData.upFileUrl}?r=file-service/upload-`
if (item.fileType === 'image') { if (item.fileType === 'image') {
url += 'img'; url += 'img'
} else if (item.fileType === 'video' || item.type === 'video') { }
url += 'video'; else if (item.fileType === 'video' || item.type === 'video') {
item.tempFilePath = item.url; url += 'video'
} else if (item.fileType === 'audio') { item.tempFilePath = item.url
url += 'audio'; }
} else { else if (item.fileType === 'audio') {
url += 'doc'; url += 'audio'
}
else {
url += 'doc'
} }
wx.uploadFile({ wx.uploadFile({
filePath: item.tempFilePath, filePath: item.tempFilePath,
name: 'file', name: 'file',
url, url,
success: (res) => { success: (res) => {
wx.hideLoading(); wx.hideLoading()
const data = JSON.parse(res.data); const data = JSON.parse(res.data)
const suffix = this.GetExtensionFileName(data.data.Url); const suffix = this.GetExtensionFileName(data.data.Url)
const expandJson = { const expandJson = {
fileId: '', fileId: '',
name: item.name || `病历相关文件.${suffix}`, name: item.name || `病历相关文件.${suffix}`,
@ -109,24 +112,26 @@ Component({
duration: 0, duration: 0,
videoUrl: '', videoUrl: '',
hash: '', hash: '',
}; }
if (item.fileType === 'image') { if (item.fileType === 'image') {
expandJson.imgUrl = data.data.Url; expandJson.imgUrl = data.data.Url
} else if (item.fileType === 'video' || item.type === 'video') { }
expandJson.imgUrl = data.data.SnapshotUrl; else if (item.fileType === 'video' || item.type === 'video') {
} else if (item.fileType === 'audio') { expandJson.imgUrl = data.data.SnapshotUrl
expandJson.duration = Number.parseInt(String(item.duration / 1000)); }
else if (item.fileType === 'audio') {
expandJson.duration = Number.parseInt(String(item.duration / 1000))
} }
resolve(expandJson); resolve(expandJson)
}, },
fail() { fail() {
wx.hideLoading(); wx.hideLoading()
reject(new Error('上传失败')); reject(new Error('上传失败'))
}, },
}); })
}); })
}, },
}, },
}); })
export {}; export {}

28
src/components/viewFile/index.js

@ -1,5 +1,5 @@
// components/viewFile/index.js // components/viewFile/index.js
const app = getApp(); const app = getApp()
Component({ Component({
/** /**
* 组件的属性列表 * 组件的属性列表
@ -25,7 +25,7 @@ Component({
* 组件的初始数据 * 组件的初始数据
*/ */
data: { data: {
Timestamp: app.globalData.Timestamp, Timestamp: app.globalData.Timestamp,
imageUrl: app.globalData.imageUrl, imageUrl: app.globalData.imageUrl,
}, },
@ -34,28 +34,28 @@ Component({
*/ */
methods: { methods: {
deleteFile(e) { deleteFile(e) {
const { index, item } = e.currentTarget.dataset; const { index, item } = e.currentTarget.dataset
this.triggerEvent("deleteFile", { this.triggerEvent('deleteFile', {
index, index,
item, item,
}); })
}, },
viewFile(e) { viewFile(e) {
const { index } = e.currentTarget.dataset; const { index } = e.currentTarget.dataset
const { fileList } = this.properties; const { fileList } = this.properties
let sources = []; const sources = []
fileList.map((e) => { fileList.map((e) => {
const obj = { const obj = {
url: e.fileUrl, url: e.fileUrl,
type: e.type, // image video type: e.type, // image video
poster: e.imgUrl, poster: e.imgUrl,
}; }
sources.push(obj); sources.push(obj)
}); })
wx.previewMedia({ wx.previewMedia({
current: index, current: index,
sources: sources, sources,
}); })
}, },
}, },
}); })

2
src/components/viewFile/index.json

@ -3,4 +3,4 @@
"usingComponents": { "usingComponents": {
"van-icon": "@vant/weapp/icon/index" "van-icon": "@vant/weapp/icon/index"
} }
} }

7
src/components/viewVideo/index.scss

@ -27,9 +27,10 @@
align-items: center; align-items: center;
flex-direction: row-reverse; flex-direction: row-reverse;
background: linear-gradient(180deg, rgba(0, 0, 0, 0.02) 0%, #000000 100%); background: linear-gradient(180deg, rgba(0, 0, 0, 0.02) 0%, #000000 100%);
>view,>image{ > view,
margin-right: 32rpx; > image {
}; margin-right: 32rpx;
}
transition: all 0.8s; transition: all 0.8s;
.time { .time {
font-size: 24rpx; font-size: 24rpx;

228
src/components/zd-navBar/navBar.js

@ -1,35 +1,35 @@
const app = getApp(); const app = getApp()
Component({ Component({
options: { options: {
multipleSlots: true, multipleSlots: true,
addGlobalClass: true, addGlobalClass: true,
}, },
properties: { properties: {
slotLeft:{ slotLeft: {
type:Boolean, type: Boolean,
value:false, value: false,
}, },
extClass: { extClass: {
type: String, type: String,
value: "", value: '',
}, },
background: { background: {
type: String, type: String,
value: "transparent", value: 'transparent',
observer: "_showChange", observer: '_showChange',
}, },
backgroundColorTop: { backgroundColorTop: {
type: String, type: String,
value: "transparent", value: 'transparent',
observer: "_showChangeBackgroundColorTop", observer: '_showChangeBackgroundColorTop',
}, },
color: { color: {
type: String, type: String,
value: "#000000", value: '#000000',
}, },
title: { title: {
type: String, type: String,
value: "", value: '',
}, },
back: { back: {
type: Boolean, type: Boolean,
@ -41,7 +41,7 @@ Component({
}, },
iconTheme: { iconTheme: {
type: String, type: String,
value: "nuohe", value: 'nuohe',
}, },
/* animated: { /* animated: {
type: Boolean, type: Boolean,
@ -61,11 +61,11 @@ Component({
value: false, value: false,
}, },
}, },
created: function () { created() {
this.getSystemInfo(); this.getSystemInfo()
}, },
attached: function () { attached() {
this.setStyle(); //设置样式 this.setStyle() // 设置样式
}, },
data: { data: {
imageUrl: app.globalData.imageUrl, imageUrl: app.globalData.imageUrl,
@ -73,50 +73,52 @@ Component({
isHome: false, isHome: false,
}, },
pageLifetimes: { pageLifetimes: {
show: function () { show() {
if (getApp().globalSystemInfo.ios) { if (getApp().globalSystemInfo.ios) {
this.getSystemInfo(); this.getSystemInfo()
this.setStyle(); //设置样式1 this.setStyle() // 设置样式1
} }
let pages = getCurrentPages(); const pages = getCurrentPages()
this.setData({ this.setData({
isHome: !pages[pages.length - 2], isHome: !pages[pages.length - 2],
}); })
}, },
hide: function () {}, hide() {},
}, },
methods: { methods: {
setStyle: function (life) { setStyle(life) {
const { statusBarHeight, navBarHeight, capsulePosition, navBarExtendHeight, ios, windowWidth } = const { statusBarHeight, navBarHeight, capsulePosition, navBarExtendHeight, ios, windowWidth }
getApp().globalSystemInfo; = getApp().globalSystemInfo
const { back, home, title } = this.data; const { back, home, title } = this.data
let rightDistance = windowWidth - capsulePosition.right; //胶囊按钮右侧到屏幕右侧的边距 const rightDistance = windowWidth - capsulePosition.right // 胶囊按钮右侧到屏幕右侧的边距
let leftWidth = windowWidth - capsulePosition.left; //胶囊按钮左侧到屏幕右侧的边距 const leftWidth = windowWidth - capsulePosition.left // 胶囊按钮左侧到屏幕右侧的边距
this.setData({ this.setData({
leftWidth: leftWidth, leftWidth,
}); })
let navigationbarinnerStyle = [ const navigationbarinnerStyle = [
`color: ${this.data.color}`, `color: ${this.data.color}`,
`background: ${this.data.background}`, `background: ${this.data.background}`,
`height:${navBarHeight + navBarExtendHeight}px`, `height:${navBarHeight + navBarExtendHeight}px`,
`padding-top:${statusBarHeight}px`, `padding-top:${statusBarHeight}px`,
`padding-right:${leftWidth}px`, `padding-right:${leftWidth}px`,
`padding-bottom:${navBarExtendHeight}px`, `padding-bottom:${navBarExtendHeight}px`,
].join(";"); ].join(';')
let navBarLeft = []; let navBarLeft = []
if ((back && !home) || (!back && home)) { if ((back && !home) || (!back && home)) {
navBarLeft = [`width:${capsulePosition.width}px`, `height:${capsulePosition.height}px`].join(";"); navBarLeft = [`width:${capsulePosition.width}px`, `height:${capsulePosition.height}px`].join(';')
} else if ((back && home) || title) { }
else if ((back && home) || title) {
navBarLeft = [ navBarLeft = [
`width:${capsulePosition.width}px`, `width:${capsulePosition.width}px`,
`height:${capsulePosition.height}px`, `height:${capsulePosition.height}px`,
`margin-left:${rightDistance}px`, `margin-left:${rightDistance}px`,
].join(";"); ].join(';')
} else { }
navBarLeft = [`width:auto`, `margin-left:0px`].join(";"); else {
navBarLeft = [`width:auto`, `margin-left:0px`].join(';')
} }
if (life === "created") { if (life === 'created') {
this.data = { this.data = {
navigationbarinnerStyle, navigationbarinnerStyle,
navBarLeft, navBarLeft,
@ -124,8 +126,9 @@ Component({
capsulePosition, capsulePosition,
navBarExtendHeight, navBarExtendHeight,
ios, ios,
}; }
} else { }
else {
this.setData({ this.setData({
navigationbarinnerStyle, navigationbarinnerStyle,
navBarLeft, navBarLeft,
@ -133,118 +136,125 @@ Component({
capsulePosition, capsulePosition,
navBarExtendHeight, navBarExtendHeight,
ios, ios,
}); })
} }
}, },
_showChange: function (value) { _showChange(value) {
this.setStyle(); this.setStyle()
}, },
// 返回事件 // 返回事件
back: function () { back() {
let pages = getCurrentPages(); const pages = getCurrentPages()
if (app.globalData.backPage) { if (app.globalData.backPage) {
wx.reLaunch({ wx.reLaunch({
url: app.globalData.backPage, url: app.globalData.backPage,
}); })
app.globalData.backPage = null; app.globalData.backPage = null
return; return
} }
if (!pages[pages.length - 2] && !app.globalData.anyWhere) { if (!pages[pages.length - 2] && !app.globalData.anyWhere) {
wx.reLaunch({ wx.reLaunch({
url: "/pages/index/index", url: '/pages/index/index',
}); })
return; return
} }
this.triggerEvent("back", { delta: this.data.delta }); this.triggerEvent('back', { delta: this.data.delta })
}, },
home: function () { home() {
wx.reLaunch({ wx.reLaunch({
url: "/pages/start/index", url: '/pages/start/index',
}); })
}, },
search: function () { search() {
this.triggerEvent("search", {}); this.triggerEvent('search', {})
}, },
getSystemInfo() { getSystemInfo() {
var app = getApp(); const app = getApp()
if (app.globalSystemInfo && !app.globalSystemInfo.ios) { if (app.globalSystemInfo && !app.globalSystemInfo.ios) {
return app.globalSystemInfo; return app.globalSystemInfo
} else { }
let systemInfo = wx.getSystemInfoSync(); else {
let ios = !!(systemInfo.system.toLowerCase().search("ios") + 1); const systemInfo = wx.getSystemInfoSync()
let rect; const ios = !!(systemInfo.system.toLowerCase().search('ios') + 1)
let rect
try { try {
rect = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null; rect = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null
if (rect === null) { if (rect === null) {
throw "getMenuButtonBoundingClientRect error"; throw 'getMenuButtonBoundingClientRect error'
} }
//取值为0的情况 有可能width不为0 top为0的情况 // 取值为0的情况 有可能width不为0 top为0的情况
if (!rect.width || !rect.top || !rect.left || !rect.height) { if (!rect.width || !rect.top || !rect.left || !rect.height) {
throw "getMenuButtonBoundingClientRect error"; throw 'getMenuButtonBoundingClientRect error'
} }
} catch (error) { }
let gap = ""; //胶囊按钮上下间距 使导航内容居中 catch (error) {
let width = 96; //胶囊的宽度 let gap = '' // 胶囊按钮上下间距 使导航内容居中
if (systemInfo.platform === "android") { let width = 96 // 胶囊的宽度
gap = 8; if (systemInfo.platform === 'android') {
width = 96; gap = 8
} else if (systemInfo.platform === "devtools") { width = 96
}
else if (systemInfo.platform === 'devtools') {
if (ios) { if (ios) {
gap = 5.5; //开发工具中ios手机 gap = 5.5 // 开发工具中ios手机
} else {
gap = 7.5; //开发工具中android和其它手机
} }
} else { else {
gap = 4; gap = 7.5 // 开发工具中android和其它手机
width = 88; }
}
else {
gap = 4
width = 88
} }
if (!systemInfo.statusBarHeight) { if (!systemInfo.statusBarHeight) {
//开启wifi的情况下修复statusBarHeight值获取不到 // 开启wifi的情况下修复statusBarHeight值获取不到
systemInfo.statusBarHeight = systemInfo.screenHeight - systemInfo.windowHeight - 20; systemInfo.statusBarHeight = systemInfo.screenHeight - systemInfo.windowHeight - 20
} }
rect = { rect = {
//获取不到胶囊信息就自定义重置一个 // 获取不到胶囊信息就自定义重置一个
bottom: systemInfo.statusBarHeight + gap + 32, bottom: systemInfo.statusBarHeight + gap + 32,
height: 32, height: 32,
left: systemInfo.windowWidth - width - 10, left: systemInfo.windowWidth - width - 10,
right: systemInfo.windowWidth - 10, right: systemInfo.windowWidth - 10,
top: systemInfo.statusBarHeight + gap, top: systemInfo.statusBarHeight + gap,
width: width, width,
}; }
console.log("error", error); console.log('error', error)
console.log("rect", rect); console.log('rect', rect)
} }
let navBarHeight = ""; let navBarHeight = ''
if (!systemInfo.statusBarHeight) { if (!systemInfo.statusBarHeight) {
systemInfo.statusBarHeight = systemInfo.screenHeight - systemInfo.windowHeight - 20; systemInfo.statusBarHeight = systemInfo.screenHeight - systemInfo.windowHeight - 20
navBarHeight = (function () { navBarHeight = (function () {
let gap = rect.top - systemInfo.statusBarHeight; const gap = rect.top - systemInfo.statusBarHeight
return 2 * gap + rect.height; return 2 * gap + rect.height
})(); })()
systemInfo.statusBarHeight = 0; systemInfo.statusBarHeight = 0
systemInfo.navBarExtendHeight = 0; //下方扩展4像素高度 防止下方边距太小 systemInfo.navBarExtendHeight = 0 // 下方扩展4像素高度 防止下方边距太小
} else { }
else {
navBarHeight = (function () { navBarHeight = (function () {
let gap = rect.top - systemInfo.statusBarHeight; const gap = rect.top - systemInfo.statusBarHeight
return systemInfo.statusBarHeight + 2 * gap + rect.height; return systemInfo.statusBarHeight + 2 * gap + rect.height
})(); })()
if (ios) { if (ios) {
systemInfo.navBarExtendHeight = 4; //下方扩展4像素高度 防止下方边距太小 systemInfo.navBarExtendHeight = 4 // 下方扩展4像素高度 防止下方边距太小
} else { }
systemInfo.navBarExtendHeight = 0; else {
systemInfo.navBarExtendHeight = 0
} }
} }
systemInfo.navBarHeight = navBarHeight; //导航栏高度不包括statusBarHeight systemInfo.navBarHeight = navBarHeight // 导航栏高度不包括statusBarHeight
systemInfo.capsulePosition = rect; //右上角胶囊按钮信息bottom: 58 height: 32 left: 317 right: 404 top: 26 width: 87 目前发现在大多机型都是固定值 为防止不一样所以会使用动态值来计算nav元素大小 systemInfo.capsulePosition = rect // 右上角胶囊按钮信息bottom: 58 height: 32 left: 317 right: 404 top: 26 width: 87 目前发现在大多机型都是固定值 为防止不一样所以会使用动态值来计算nav元素大小
systemInfo.ios = ios; //是否ios systemInfo.ios = ios // 是否ios
app.globalSystemInfo = systemInfo; //将信息保存到全局变量中,后边再用就不用重新异步获取了 app.globalSystemInfo = systemInfo // 将信息保存到全局变量中,后边再用就不用重新异步获取了
//console.log('systemInfo', systemInfo); // console.log('systemInfo', systemInfo);
return systemInfo; return systemInfo
} }
}, },
}, },
}); })

2
src/components/zd-navBar/navBar.scss

@ -75,7 +75,7 @@ page {
} }
.lxy-nav-bar__buttons::after { .lxy-nav-bar__buttons::after {
position: absolute; position: absolute;
content: ""; content: '';
width: 1rpx; width: 1rpx;
height: 18.4px; height: 18.4px;
background: rgba(204, 204, 204, 0.6); background: rgba(204, 204, 204, 0.6);

164
src/components/zdUploadFile/index.js

@ -1,5 +1,5 @@
// components/uploadFile/index.js // components/uploadFile/index.js
const app = getApp(); const app = getApp()
Component({ Component({
/** /**
* 组件的属性列表 * 组件的属性列表
@ -17,17 +17,17 @@ Component({
}, },
accept: { accept: {
type: String, type: String,
value: "media", value: 'media',
}, },
fileTypes: { fileTypes: {
// 上传类型 // 上传类型
type: Array, type: Array,
value: ["image", "video"], value: ['image', 'video'],
}, },
// 拍照和相机 // 拍照和相机
sourceType: { sourceType: {
type: Array, type: Array,
value: ["album", "camera"], value: ['album', 'camera'],
}, },
// 是否可以删除 // 是否可以删除
canDelete: { canDelete: {
@ -67,62 +67,64 @@ Component({
*/ */
methods: { methods: {
viewFile(e) { viewFile(e) {
const { index } = e.currentTarget.dataset; const { index } = e.currentTarget.dataset
const { fileList } = this.properties; const { fileList } = this.properties
let sources = []; const sources = []
fileList.map((e) => { fileList.map((e) => {
const obj = { const obj = {
url: e.fileUrl, url: e.fileUrl,
type: e.type, // image video type: e.type, // image video
poster: e.imgUrl, poster: e.imgUrl,
}; }
sources.push(obj); sources.push(obj)
}); })
wx.previewMedia({ wx.previewMedia({
current: index, current: index,
sources: sources, sources,
}); })
}, },
deleteFile(e) { deleteFile(e) {
const { index, item } = e.currentTarget.dataset; const { index, item } = e.currentTarget.dataset
this.triggerEvent("deleteFile", { this.triggerEvent('deleteFile', {
index, index,
item, item,
}); })
}, },
downFile(e) { downFile(e) {
const { item } = e.currentTarget.dataset; const { item } = e.currentTarget.dataset
wx.showToast({ wx.showToast({
title: "正在下载,请稍后...", title: '正在下载,请稍后...',
icon: "none", icon: 'none',
}); })
wx.downloadFile({ wx.downloadFile({
url: item.fileUrl, url: item.fileUrl,
success(res) { success(res) {
if (item.type === "image") { if (item.type === 'image') {
wx.saveImageToPhotosAlbum({ wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath, filePath: res.tempFilePath,
success: () => { success: () => {
wx.showToast({ wx.showToast({
title: "下载成功", title: '下载成功',
}); })
}, },
}); })
} else if (item.type === "video") { }
else if (item.type === 'video') {
wx.saveVideoToPhotosAlbum({ wx.saveVideoToPhotosAlbum({
filePath: res.tempFilePath, filePath: res.tempFilePath,
success: () => { success: () => {
wx.showToast({ wx.showToast({
title: "下载成功", title: '下载成功',
}); })
}, },
}); })
} else { }
else {
wx.showToast({ wx.showToast({
title: "附件请到pc端下载!", title: '附件请到pc端下载!',
icon: "none", icon: 'none',
}); })
// wx.saveFile({ // wx.saveFile({
// tempFilePath: res.tempFilePath, // tempFilePath: res.tempFilePath,
// success: () => { // success: () => {
@ -136,96 +138,96 @@ Component({
// }) // })
} }
}, },
}); })
}, },
uploadFile(item) { uploadFile(item) {
return new Promise((resolve, resject) => { return new Promise((resolve, resject) => {
let url = `${app.globalData.upFileUrl}?r=file-service/upload-`; let url = `${app.globalData.upFileUrl}?r=file-service/upload-`
if (item.fileType === "image") { if (item.fileType === 'image') {
url += "img"; url += 'img'
} }
if (item.fileType === "video") { if (item.fileType === 'video') {
url += "video"; url += 'video'
} }
let that = this; const that = this
wx.uploadFile({ wx.uploadFile({
filePath: item.tempFilePath, filePath: item.tempFilePath,
name: "file", name: 'file',
url: url, url,
success(res) { success(res) {
let data = JSON.parse(res.data); const data = JSON.parse(res.data)
let expandJson = { const expandJson = {
fileId: "", fileId: '',
name: data.data.Url, name: data.data.Url,
size: (item.size / 1024).toFixed(2), size: (item.size / 1024).toFixed(2),
fileUrl: data.data.Url, fileUrl: data.data.Url,
suffix: that.GetExtensionFileName(data.data.Url), suffix: that.GetExtensionFileName(data.data.Url),
type: item.fileType, type: item.fileType,
};
if (item.fileType === "image") {
expandJson.imgUrl = data.data.Url;
} }
if (item.fileType === "video") { if (item.fileType === 'image') {
expandJson.imgUrl = data.data.SnapshotUrl; expandJson.imgUrl = data.data.Url
}
if (item.fileType === 'video') {
expandJson.imgUrl = data.data.SnapshotUrl
} }
resolve(expandJson); resolve(expandJson)
}, },
fail() { fail() {
resject(); resject()
}, },
}); })
}); })
}, },
GetExtensionFileName(pathfilename) { GetExtensionFileName(pathfilename) {
var reg = /(\\+)/g; const reg = /(\\+)/g
var pString = pathfilename.replace(reg, "#"); //用正则表达式来将\或\\替换成# const pString = pathfilename.replace(reg, '#') // 用正则表达式来将\或\\替换成#
var arr = pString.split("#"); // 以“#”为分隔符,将字符分解为数组 例如 D Program Files bg.png const arr = pString.split('#') // 以“#”为分隔符,将字符分解为数组 例如 D Program Files bg.png
var lastString = arr[arr.length - 1]; //取最后一个字符 const lastString = arr[arr.length - 1] // 取最后一个字符
var arr2 = lastString.split("."); // 再以"."作为分隔符 const arr2 = lastString.split('.') // 再以"."作为分隔符
return arr2[arr2.length - 1]; //将后缀名返回出来 return arr2[arr2.length - 1] // 将后缀名返回出来
}, },
upFile(data) { upFile(data) {
wx.showLoading({ wx.showLoading({
title: "正在上传", title: '正在上传',
}); })
let apiArr = []; const apiArr = []
data.map((e) => { data.map((e) => {
apiArr.push(this.uploadFile(e)); apiArr.push(this.uploadFile(e))
}); })
Promise.all(apiArr) Promise.all(apiArr)
.then((res) => { .then((res) => {
wx.hideLoading({ wx.hideLoading({
success: () => { success: () => {
this.triggerEvent("setData", res); this.triggerEvent('setData', res)
}, },
}); })
}) })
.catch(() => { .catch(() => {
wx.showToast({ wx.showToast({
title: "上传失败", title: '上传失败',
icon: "error", icon: 'error',
}); })
}); })
}, },
selectFile() { selectFile() {
let { fileList, maxNum, sourceType, fileTypes, count = 0 } = this.properties; let { fileList, maxNum, sourceType, fileTypes, count = 0 } = this.properties
var that = this; const that = this
if (maxNum >= 0 && count == 0) { if (maxNum >= 0 && count == 0) {
count = maxNum - fileList.length; count = maxNum - fileList.length
} }
this.triggerEvent("choose"); this.triggerEvent('choose')
wx.chooseMedia({ wx.chooseMedia({
mediaType: fileTypes, mediaType: fileTypes,
count: count, count,
sourceType: sourceType, sourceType,
sizeType: ["original"], sizeType: ['original'],
success(res) { success(res) {
res.tempFiles.map((e) => { res.tempFiles.map((e) => {
e.fileType = e.fileType || res.type; e.fileType = e.fileType || res.type
}); })
that.upFile(res.tempFiles); that.upFile(res.tempFiles)
}, },
}); })
}, },
}, },
}); })

2
src/doc/pages/doc1/index.scss

@ -1,3 +1,3 @@
.page{ .page {
padding: 0 40rpx; padding: 0 40rpx;
} }

6
src/doc/pages/doc1/index.ts

File diff suppressed because one or more lines are too long

2
src/doc/pages/doc2/index.scss

@ -1,3 +1,3 @@
.mp-html{ .mp-html {
padding: 20rpx 40rpx; padding: 20rpx 40rpx;
} }

5184
src/gift/compontnts/echart/echarts.js

File diff suppressed because one or more lines are too long

2
src/pages/d_invite/index.scss

@ -1,4 +1,4 @@
page{ page {
background-color: #d68dfc; background-color: #d68dfc;
} }
.page { .page {

8
src/pages/d_noteDetail/index.wxml

@ -13,27 +13,27 @@
当前记录对应的替妥尤单抗使用次数: 当前记录对应的替妥尤单抗使用次数:
<text class="num">{{recordDetail.treatmentCount}}</text> <text class="num">{{recordDetail.treatmentCount}}</text>
</view> </view>
<view class="banner" wx:if="{{recordDetail.leftEye || recordDetail.rightEye || recordDetail.interorbitalDistance}}"> <view class="banner" wx:if="{{recordDetail.leftEye != null || recordDetail.rightEye != null || recordDetail.interorbitalDistance != null}}">
<view class="title">眼球突出度测量记录</view> <view class="title">眼球突出度测量记录</view>
<view class="row"> <view class="row">
<view class="col"> <view class="col">
<view class="name">右眼</view> <view class="name">右眼</view>
<view class="content"> <view class="content">
<view class="num">{{recordDetail.rightEye || '--'}}</view> <view class="num">{{recordDetail.rightEye != null ? recordDetail.rightEye : '--'}}</view>
<view class="sub">MM</view> <view class="sub">MM</view>
</view> </view>
</view> </view>
<view class="col"> <view class="col">
<view class="name">眶间距</view> <view class="name">眶间距</view>
<view class="content"> <view class="content">
<view class="num">{{recordDetail.interorbitalDistance || '--'}}</view> <view class="num">{{recordDetail.interorbitalDistance != null ? recordDetail.interorbitalDistance : '--'}}</view>
<view class="sub">MM</view> <view class="sub">MM</view>
</view> </view>
</view> </view>
<view class="col"> <view class="col">
<view class="name">左眼</view> <view class="name">左眼</view>
<view class="content"> <view class="content">
<view class="num">{{recordDetail.leftEye || '--'}}</view> <view class="num">{{recordDetail.leftEye != null ? recordDetail.leftEye : '--'}}</view>
<view class="sub">MM</view> <view class="sub">MM</view>
</view> </view>
</view> </view>

10
src/pages/d_noteDiff/index.wxml

@ -48,29 +48,29 @@
</view> </view>
<view class="tags"> <view class="tags">
<view wx:if="{{item.isBaseline === 1}}" class="tag tag1">基准照片</view> <view wx:if="{{item.isBaseline === 1}}" class="tag tag1">基准照片</view>
<view class="tag tag2">替妥尤单抗:{{item.treatmentCount}}</view> <view class="tag tag2" wx:if="{{item.treatmentCount > 0}}">替妥尤单抗:{{item.treatmentCount >= 9 ? '>8' : item.treatmentCount}}</view>
</view> </view>
<view class="photo-card"> <view class="photo-card">
<image class="photo" src="{{item.photoUrl}}" mode="aspectFill"></image> <image class="photo" src="{{item.photoUrl}}" mode="aspectFill"></image>
<view class="row" wx:if="{{item.leftEye || item.rightEye || item.interorbitalDistance}}"> <view class="row" wx:if="{{item.leftEye != null || item.rightEye != null || item.interorbitalDistance != null}}">
<view class="col"> <view class="col">
<view class="name">右眼</view> <view class="name">右眼</view>
<view class="content"> <view class="content">
<view class="num">{{item.rightEye || '--'}}</view> <view class="num">{{item.rightEye != null ? item.rightEye : '--'}}</view>
<view class="sub">MM</view> <view class="sub">MM</view>
</view> </view>
</view> </view>
<view class="col"> <view class="col">
<view class="name">眶间距</view> <view class="name">眶间距</view>
<view class="content"> <view class="content">
<view class="num">{{item.interorbitalDistance || '--'}}</view> <view class="num">{{item.interorbitalDistance != null ? item.interorbitalDistance : '--'}}</view>
<view class="sub">MM</view> <view class="sub">MM</view>
</view> </view>
</view> </view>
<view class="col"> <view class="col">
<view class="name">左眼</view> <view class="name">左眼</view>
<view class="content"> <view class="content">
<view class="num">{{item.leftEye || '--'}}</view> <view class="num">{{item.leftEye != null ? item.leftEye : '--'}}</view>
<view class="sub">MM</view> <view class="sub">MM</view>
</view> </view>
</view> </view>

6
src/pages/d_noteDiffData/index.wxml

@ -28,9 +28,9 @@
<view class="tr" wx:for="{{dataList}}" wx:key="recordId"> <view class="tr" wx:for="{{dataList}}" wx:key="recordId">
<view class="td td-date">{{item.recordDate}}</view> <view class="td td-date">{{item.recordDate}}</view>
<view class="td td-eye"> <view class="td td-eye">
<view class="td-eye-item">{{item.leftEye || '--'}}</view> <view class="td-eye-item">{{item.leftEye != null ? item.leftEye : '--'}}</view>
<view class="td-eye-item">{{item.interorbitalDistance || '--'}}</view> <view class="td-eye-item">{{item.interorbitalDistance != null ? item.interorbitalDistance : '--'}}</view>
<view class="td-eye-item">{{item.rightEye || '--'}}</view> <view class="td-eye-item">{{item.rightEye != null ? item.rightEye : '--'}}</view>
</view> </view>
<view class="td td-count">{{item.treatmentCount}}</view> <view class="td td-count">{{item.treatmentCount}}</view>
</view> </view>

2
src/pages/d_noteDiffEdit/index.ts

@ -175,7 +175,7 @@ Page({
const imageList = photos.map((item) => { const imageList = photos.map((item) => {
const label = item.isBaseline === 1 const label = item.isBaseline === 1
? `基准照片 ${item.recordDate}` ? `基准照片 ${item.recordDate}`
: `对比照片 ${item.recordDate} 替妥尤单抗:${item.treatmentCount}` : `对比照片 ${item.recordDate} 替妥尤单抗:${item.treatmentCount >= 9 ? '>8' : item.treatmentCount}`
return { return {
src: item.croppedUrl || item.photoUrl, src: item.croppedUrl || item.photoUrl,
time: label, time: label,

2
src/pages/d_noteDiffEdit/index.wxml

@ -19,7 +19,7 @@
</view> </view>
<view class="tags"> <view class="tags">
<view wx:if="{{item.isBaseline === 1}}" class="tag tag1">基准照片</view> <view wx:if="{{item.isBaseline === 1}}" class="tag tag1">基准照片</view>
<view class="tag tag2">替妥尤单抗:{{item.treatmentCount}}</view> <view class="tag tag2" wx:if="{{item.treatmentCount > 0}}">替妥尤单抗:{{item.treatmentCount >= 9 ? '>8' : item.treatmentCount}}</view>
</view> </view>
<view class="photo-card"> <view class="photo-card">
<image class="photo" src="{{item.croppedUrl || item.photoUrl}}" mode="aspectFill"></image> <image class="photo" src="{{item.croppedUrl || item.photoUrl}}" mode="aspectFill"></image>

4
src/pages/d_noteList/index.wxml

@ -9,10 +9,10 @@
<view wx:if="{{item.isBaseline === 1}}" class="benchmark" style="background: url('{{imageUrl}}bg50.png?t={{Timestamp}}') no-repeat top center/100%"> <view wx:if="{{item.isBaseline === 1}}" class="benchmark" style="background: url('{{imageUrl}}bg50.png?t={{Timestamp}}') no-repeat top center/100%">
基准照 基准照
</view> </view>
<image class="photo" src="{{item.firstPhotoUrl || imageUrl + 'icon143.png?t=' + Timestamp}}"></image> <image class="photo" mode="aspectFill" src="{{item.firstPhotoUrl || imageUrl + 'icon143.png?t=' + Timestamp}}"></image>
<view class="wrap"> <view class="wrap">
<view class="date">{{item.recordDate}}</view> <view class="date">{{item.recordDate}}</view>
<view class="tag">替妥尤单抗:{{item.treatmentCount}}</view> <view class="tag" wx:if="{{item.treatmentCount > 0}}">替妥尤单抗:{{item.treatmentCount >= 9 ? '>8' : item.treatmentCount}}</view>
<view class="rotate">已上传{{item.photoCount}}个角度</view> <view class="rotate">已上传{{item.photoCount}}个角度</view>
</view> </view>
<image class="more" src="{{imageUrl}}icon148.png?t={{Timestamp}}"></image> <image class="more" src="{{imageUrl}}icon148.png?t={{Timestamp}}"></image>

4
src/pages/d_patientDetail/index.wxml

@ -86,10 +86,10 @@
> >
基准照 基准照
</view> </view>
<image class="photo" src="{{proptosisDetail.firstPhotoUrl || imageUrl + 'icon143.png?t=' + Timestamp}}"></image> <image class="photo" mode="aspectFill" src="{{proptosisDetail.firstPhotoUrl || imageUrl + 'icon143.png?t=' + Timestamp}}"></image>
<view class="wrap"> <view class="wrap">
<view class="date">{{proptosisDetail.recordDate}}</view> <view class="date">{{proptosisDetail.recordDate}}</view>
<view class="tag">替妥尤单抗:{{proptosisDetail.treatmentCount}}</view> <view class="tag" wx:if="{{proptosisDetail.treatmentCount > 0}}">替妥尤单抗:{{proptosisDetail.treatmentCount >= 9 ? '>8' : proptosisDetail.treatmentCount}}</view>
<view class="rotate">已上传{{proptosisDetail.photoCount}}个角度</view> <view class="rotate">已上传{{proptosisDetail.photoCount}}个角度</view>
</view> </view>
<image class="more" src="/images/icon168.png"></image> <image class="more" src="/images/icon168.png"></image>

2
src/pages/d_patientHormones/index.ts

@ -29,7 +29,7 @@ Page({
page: newPage, page: newPage,
}, },
}).then((res) => { }).then((res) => {
let list = res.page == 1 ? res.list : [...this.data.list, ...res.list] const list = res.page == 1 ? res.list : [...this.data.list, ...res.list]
this.setData({ this.setData({
list, list,
pagination: { pagination: {

4
src/pages/d_userInfo/index.scss

@ -155,7 +155,7 @@ page {
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
background: linear-gradient( 197deg, #FFBCF9 0%, #B982FF 100%); background: linear-gradient(197deg, #ffbcf9 0%, #b982ff 100%);
font-size: 36rpx; font-size: 36rpx;
color: #fff; color: #fff;
border-radius: 64rpx 64rpx 64rpx 64rpx; border-radius: 64rpx 64rpx 64rpx 64rpx;
@ -188,7 +188,7 @@ page {
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
background: linear-gradient( 197deg, #FFBCF9 0%, #B982FF 100%); background: linear-gradient(197deg, #ffbcf9 0%, #b982ff 100%);
font-size: 36rpx; font-size: 36rpx;
color: #fff; color: #fff;
border-radius: 64rpx 64rpx 64rpx 64rpx; border-radius: 64rpx 64rpx 64rpx 64rpx;

13
src/pages/d_userInfo/index.ts

@ -57,7 +57,7 @@ Page({
onLoad() {}, onLoad() {},
onShow() { onShow() {
app.waitLogin({ type: [2] }).then((_res) => { app.waitLogin({ type: [2] }).then((_res) => {
app.mpBehavior({ doctor:true, PageName: 'PG_DoctorInfoDetails' }) app.mpBehavior({ doctor: true, PageName: 'PG_DoctorInfoDetails' })
this.getDetail() this.getDetail()
}) })
}, },
@ -72,7 +72,8 @@ Page({
let weekName = '' let weekName = ''
if (res.doctor.ClinicType == 2) { if (res.doctor.ClinicType == 2) {
weekName = res.doctor.Clinic weekName = res.doctor.Clinic
} else { }
else {
;(res.doctor.Clinic ? res.doctor.Clinic : []).forEach((subItem: any) => { ;(res.doctor.Clinic ? res.doctor.Clinic : []).forEach((subItem: any) => {
if (subItem.timeType == 1) { if (subItem.timeType == 1) {
ClinicList[subItem.weekday - 1].timeTypeActive1 = true ClinicList[subItem.weekday - 1].timeTypeActive1 = true
@ -83,7 +84,7 @@ Page({
}) })
weekName = (res.doctor.Clinic ? res.doctor.Clinic : []) weekName = (res.doctor.Clinic ? res.doctor.Clinic : [])
.map((subItem: { weekday: string | number; timeType: string | number }) => { .map((subItem: { weekday: string | number, timeType: string | number }) => {
const week = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] const week = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
const timeDay = { 1: '上午', 2: '下午' } const timeDay = { 1: '上午', 2: '下午' }
return `${week[Number(subItem.weekday) - 1]}${timeDay[subItem.timeType]}` return `${week[Number(subItem.weekday) - 1]}${timeDay[subItem.timeType]}`
@ -110,7 +111,8 @@ Page({
'doctor.Clinic': '', 'doctor.Clinic': '',
'doctor.weekName': '', 'doctor.weekName': '',
}) })
} else { }
else {
this.setData({ this.setData({
'doctor.ClinicType': 1, 'doctor.ClinicType': 1,
'doctor.Clinic': [], 'doctor.Clinic': [],
@ -149,7 +151,8 @@ Page({
let Clinic = '' let Clinic = ''
if (doctor.ClinicType == 2) { if (doctor.ClinicType == 2) {
Clinic = PopupClinic Clinic = PopupClinic
} else { }
else {
const ClinicList = this.data.ClinicList const ClinicList = this.data.ClinicList
Clinic = ClinicList.reduce((pre, cur) => { Clinic = ClinicList.reduce((pre, cur) => {
if (cur.timeTypeActive1) { if (cur.timeTypeActive1) {

2
src/pages/information/index.json

@ -1,5 +1,5 @@
{ {
"usingComponents": { "usingComponents": {
"navbar":"/components/navbar/index" "navbar": "/components/navbar/index"
} }
} }

7
src/pages/informationDetail/index.ts

@ -40,7 +40,7 @@ Page({
id: options.id, id: options.id,
}) })
app.waitLogin({ type: [2] }).then(() => { app.waitLogin({ type: [2] }).then(() => {
app.mpBehavior({ doctor:true, PageName: 'PG_LibraryDetails' }) app.mpBehavior({ doctor: true, PageName: 'PG_LibraryDetails' })
app.oldMpBehavior({ PositionId: '1', OperateType: '1', OperateId: options.id as string }) app.oldMpBehavior({ PositionId: '1', OperateType: '1', OperateId: options.id as string })
this.getDetail() this.getDetail()
}) })
@ -137,7 +137,8 @@ Page({
wx.hideLoading() wx.hideLoading()
}, },
}) })
} else { }
else {
wx.hideLoading() wx.hideLoading()
wx.showToast({ wx.showToast({
title: '下载文件失败', title: '下载文件失败',
@ -161,7 +162,7 @@ Page({
}, },
onShareAppMessage() { onShareAppMessage() {
app.mpBehavior({ doctor:true, PageName: 'BTN_LibraryDetailsShare' }) app.mpBehavior({ doctor: true, PageName: 'BTN_LibraryDetailsShare' })
const { Title, CoverImgUrl, Id } = this.data.detail const { Title, CoverImgUrl, Id } = this.data.detail
app.oldMpBehavior({ PositionId: '1', OperateType: '3', OperateId: Id as string }) app.oldMpBehavior({ PositionId: '1', OperateType: '3', OperateId: Id as string })
return { return {

2
src/pages/login/index.scss

@ -41,7 +41,7 @@ page {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
background: linear-gradient( 197deg, #FFBCF9 0%, #B982FF 100%); background: linear-gradient(197deg, #ffbcf9 0%, #b982ff 100%);
border-radius: 84rpx 84rpx 84rpx 84rpx; border-radius: 84rpx 84rpx 84rpx 84rpx;
} }
.divider { .divider {

42
src/pages/message/index.ts

@ -1,5 +1,5 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
const dayjs = require('dayjs'); const dayjs = require('dayjs')
Page({ Page({
data: { data: {
@ -12,22 +12,22 @@ Page({
}, },
onLoad() { onLoad() {
app.waitLogin({ type: [2] }).then(() => { app.waitLogin({ type: [2] }).then(() => {
this.getList(); this.getList()
}); })
}, },
handleDetail(e) { handleDetail(e) {
const { index } = e.currentTarget.dataset; const { index } = e.currentTarget.dataset
const { Id, Url } = this.data.list[index]; const { Id, Url } = this.data.list[index]
app.oldMpBehavior({ PositionId: '4', OperateType: '1', OperateId: Id }); app.oldMpBehavior({ PositionId: '4', OperateType: '1', OperateId: Id })
if (Url) { if (Url) {
wx.navigateTo({ wx.navigateTo({
url: Url, url: Url,
fail() { fail() {
wx.reLaunch({ wx.reLaunch({
url: Url, url: Url,
}); })
}, },
}); })
} }
}, },
getList(newPage = 1) { getList(newPage = 1) {
@ -38,32 +38,32 @@ Page({
page: newPage, page: newPage,
}, },
}).then((res) => { }).then((res) => {
const list = res.page === 1 ? res.list : [...this.data.list, ...res.list]; const list = res.page === 1 ? res.list : [...this.data.list, ...res.list]
this.setData({ this.setData({
total: res.count, total: res.count,
list: list.map((item) => { list: list.map((item) => {
item.year = dayjs(item.PublishDate).format('YYYY'); item.year = dayjs(item.PublishDate).format('YYYY')
item.month = dayjs(item.PublishDate).format('MM'); item.month = dayjs(item.PublishDate).format('MM')
item.day = dayjs(item.PublishDate).format('DD'); item.day = dayjs(item.PublishDate).format('DD')
return item; return item
}), }),
pagination: { pagination: {
page: res.page, page: res.page,
pages: res.pages, pages: res.pages,
count: res.count, count: res.count,
}, },
}); })
wx.setNavigationBarTitle({ wx.setNavigationBarTitle({
title: `消息(${res.count}`, title: `消息(${res.count}`,
}); })
}); })
}, },
onReachBottom() { onReachBottom() {
const { page, pages } = this.data.pagination; const { page, pages } = this.data.pagination
if (pages > page) { if (pages > page) {
this.getList(page + 1); this.getList(page + 1)
} }
}, },
}); })
export {}; export {}

2
src/pages/start/index.scss

@ -1,4 +1,4 @@
.page{ .page {
width: 100vw; width: 100vw;
height: 100vh; height: 100vh;
} }

8
src/pages/webview/index.ts

@ -1,4 +1,4 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
Page({ Page({
data: { data: {
@ -7,8 +7,8 @@ Page({
onLoad(options) { onLoad(options) {
this.setData({ this.setData({
src: decodeURIComponent(options.url || ''), src: decodeURIComponent(options.url || ''),
}); })
}, },
}); })
export {}; export {}

3
src/patient/components/camera/index.json

@ -3,6 +3,7 @@
"usingComponents": { "usingComponents": {
"van-icon": "@vant/weapp/icon/index", "van-icon": "@vant/weapp/icon/index",
"van-button": "@vant/weapp/button/index", "van-button": "@vant/weapp/button/index",
"van-popup": "@vant/weapp/popup/index" "van-popup": "@vant/weapp/popup/index",
"navbar": "/components/navbar/index"
} }
} }

3
src/patient/components/camera/index.scss

@ -12,6 +12,7 @@
.camera-container { .camera-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
box-sizing: border-box;
} }
.camera { .camera {
@ -21,7 +22,7 @@
text-align: center; text-align: center;
.example { .example {
position: relative; position: relative;
margin: 120rpx 32rpx 0; margin: 20rpx 32rpx 0;
width: 202rpx; width: 202rpx;
height: 56rpx; height: 56rpx;
font-size: 32rpx; font-size: 32rpx;

7
src/patient/components/camera/index.ts

@ -29,6 +29,7 @@ Component({
flash: 'off' as 'off' | 'auto' | 'on', flash: 'off' as 'off' | 'auto' | 'on',
previewImage: '', previewImage: '',
sessionIdCache: '', sessionIdCache: '',
navHeight: wx.getSystemInfoSync().statusBarHeight + 44,
selectShow: false, selectShow: false,
exampleShow: false, exampleShow: false,
@ -74,11 +75,11 @@ Component({
exampleSrc: 'note-demo5', exampleSrc: 'note-demo5',
}, },
6: { 6: {
src: 'note-camera6', src: 'note-camera7',
exampleSrc: 'note-demo6', exampleSrc: 'note-demo6',
}, },
7: { 7: {
src: 'note-camera7', src: 'note-camera6',
exampleSrc: 'note-demo7', exampleSrc: 'note-demo7',
}, },
8: { 8: {
@ -128,6 +129,7 @@ Component({
handleSelect(type: number) { handleSelect(type: number) {
this.setData({ this.setData({
type, type,
exampleShow: false,
}) })
// 如果设置了只使用相机,直接打开相机 // 如果设置了只使用相机,直接打开相机
if (this.properties.onlyCamera) { if (this.properties.onlyCamera) {
@ -208,6 +210,7 @@ Component({
}, },
takePhoto() { takePhoto() {
this.setData({ exampleShow: false })
const ctx = wx.createCameraContext() const ctx = wx.createCameraContext()
ctx.takePhoto({ ctx.takePhoto({

9
src/patient/components/camera/index.wxml

@ -1,8 +1,11 @@
<view class="camera-container" wx:if="{{visible}}"> <view class="camera-container" wx:if="{{visible}}">
<navbar fixed title="" zIndex="1001" custom-style="background:transparent" bind:click-left="handleHideCamera">
<van-icon name="arrow-left" slot="left" size="18px" color="#fff" bind:tap="handleHideCamera" />
</navbar>
<camera class="camera" device-position="{{devicePosition}}" flash="{{flash}}" binderror="onCameraError"> <camera class="camera" device-position="{{devicePosition}}" flash="{{flash}}" binderror="onCameraError">
<view <view
class="camera-container" class="camera-container"
style="background: url('{{imageUrl}}camera-bg.png?t={{Timestamp}}') no-repeat center/100%" style="background: url('{{imageUrl}}camera-bg.png?t={{Timestamp}}') no-repeat center/100%;padding-top:{{navHeight}}px;"
> >
<view class="example {{exampleShow && 'active'}}" bind:tap="handleExample"> <view class="example {{exampleShow && 'active'}}" bind:tap="handleExample">
<image class="icon" src="{{imageUrl}}icon159.png?t={{Timestamp}}"></image> <image class="icon" src="{{imageUrl}}icon159.png?t={{Timestamp}}"></image>
@ -24,10 +27,10 @@
<image class="icon9-1" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image> <image class="icon9-1" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image>
<image class="icon9-2" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image> <image class="icon9-2" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image>
</block> </block>
<image wx:elif="{{type==10}}" class="icon10" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image> <image wx:elif="{{type==10}}" class="icon13" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image>
<image wx:elif="{{type==11}}" class="icon11" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image> <image wx:elif="{{type==11}}" class="icon11" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image>
<image wx:elif="{{type==12}}" class="icon12" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image> <image wx:elif="{{type==12}}" class="icon12" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image>
<image wx:elif="{{type==13}}" class="icon13" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image> <image wx:elif="{{type==13}}" class="icon10" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image>
<block wx:elif="{{type==14}}"> <block wx:elif="{{type==14}}">
<image class="icon14-1" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image> <image class="icon14-1" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image>
<image class="icon14-2" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image> <image class="icon14-2" src="{{imageUrl}}icon163.png?t={{Timestamp}}"></image>

2
src/patient/pages/cancellation/index.scss

@ -37,7 +37,7 @@ page {
text-align: center; text-align: center;
color: #fff; color: #fff;
line-height: 88rpx; line-height: 88rpx;
background: linear-gradient( 197deg, #FFBCF9 0%, #B982FF 100%); background: linear-gradient(197deg, #ffbcf9 0%, #b982ff 100%);
border-radius: 42rpx; border-radius: 42rpx;
} }
} }

34
src/patient/pages/cancellation/index.ts

@ -1,21 +1,21 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
Page({ Page({
data: { data: {
durgInfo: {}, durgInfo: {},
}, },
onLoad() { onLoad() {
const _this = this; const _this = this
const eventChannel = this.getOpenerEventChannel(); const eventChannel = this.getOpenerEventChannel()
eventChannel.on('durgInfo', function (data) { eventChannel.on('durgInfo', (data) => {
console.log(data); console.log(data)
_this.setData({ _this.setData({
durgInfo: data, durgInfo: data,
}); })
}); })
}, },
handleBack() { handleBack() {
wx.navigateBack(); wx.navigateBack()
}, },
handleCancellation() { handleCancellation() {
wx.showModal({ wx.showModal({
@ -30,19 +30,19 @@ Page({
data: {}, data: {},
loading: true, loading: true,
}).then(() => { }).then(() => {
app.globalData.backPage = ''; app.globalData.backPage = ''
app.globalData.loginState = ''; app.globalData.loginState = ''
app.globalData.userInfo = {}; app.globalData.userInfo = {}
app.startLogin(() => { app.startLogin(() => {
wx.reLaunch({ wx.reLaunch({
url: '/patient/pages/login/index', url: '/patient/pages/login/index',
}); })
}); })
}); })
} }
}, },
}); })
}, },
}); })
export {}; export {}

2
src/patient/pages/certPending/index.scss

@ -65,7 +65,7 @@
width: 300rpx; width: 300rpx;
height: 300rpx; height: 300rpx;
} }
.tip{ .tip {
margin-top: 87rpx; margin-top: 87rpx;
font-size: 28rpx; font-size: 28rpx;
color: #666666; color: #666666;

32
src/patient/pages/certPending/index.ts

@ -1,33 +1,33 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
Page({ Page({
data: {}, data: {},
onLoad() { onLoad() {
this.getCode(); this.getCode()
}, },
handleVisitors() { handleVisitors() {
app.globalData.anyWhere = true; app.globalData.anyWhere = true
let backPage = app.globalData.backPage; let backPage = app.globalData.backPage
app.globalData.backPage = ""; app.globalData.backPage = ''
if (backPage && !backPage.includes("liveResult")) { if (backPage && !backPage.includes('liveResult')) {
backPage = ""; backPage = ''
} }
wx.reLaunch({ wx.reLaunch({
url: backPage || "/patient/pages/index/index", url: backPage || '/patient/pages/index/index',
}); })
}, },
getCode() { getCode() {
wx.ajax({ wx.ajax({
method: "GET", method: 'GET',
url: "?r=zd/common/get-channel-wx-code", url: '?r=zd/common/get-channel-wx-code',
data: { data: {
ChannelType: "11", ChannelType: '11',
Id: "", Id: '',
}, },
}).then((res) => { }).then((res) => {
this.setData({ this.setData({
qrCode: res, qrCode: res,
}); })
}); })
}, },
}); })

2
src/patient/pages/certReslove/index.scss

@ -81,7 +81,7 @@
border-radius: 100rpx; border-radius: 100rpx;
font-size: 34rpx; font-size: 34rpx;
font-weight: bold; font-weight: bold;
background: linear-gradient( 197deg, #FFBCF9 0%, #B982FF 100%); background: linear-gradient(197deg, #ffbcf9 0%, #b982ff 100%);
color: #fff; color: #fff;
} }
} }

81
src/patient/pages/changePhone/index.ts

@ -1,66 +1,67 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
let timer = null as null | number; let timer = null as null | number
Page({ Page({
data: { data: {
mobile: "", mobile: '',
code: "", code: '',
codeText: "发送验证码", codeText: '发送验证码',
}, },
onLoad() {}, onLoad() {},
getCode() { getCode() {
if (timer) return; if (timer)
const mobile = this.data.mobile; return
const mobile = this.data.mobile
if (!mobile) { if (!mobile) {
wx.showToast({ wx.showToast({
title: "手机号不能为空", title: '手机号不能为空',
icon: "none", icon: 'none',
}); })
return; return
} }
// 验证手机号 // 验证手机号
if (!/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(mobile)) { if (!/^(13\d|14[579]|15[0-3,5-9]|166|17[0135-8]|18\d|19[89])\d{8}$/.test(mobile)) {
wx.showToast({ wx.showToast({
title: "手机号格式不正确", title: '手机号格式不正确',
icon: "none", icon: 'none',
}); })
return; return
} }
wx.ajax({ wx.ajax({
method: "POST", method: 'POST',
url: "?r=zd/login/send-verify-code", url: '?r=zd/login/send-verify-code',
data: { data: {
mobile, mobile,
}, },
}).then((res) => { }).then((res) => {
console.log(res); console.log(res)
wx.showToast({ wx.showToast({
icon: "none", icon: 'none',
title: "验证码已发送~", title: '验证码已发送~',
}); })
let time = 60; let time = 60
timer = setInterval(() => { timer = setInterval(() => {
time--; time--
this.setData({ this.setData({
codeText: time + "s后重新发送", codeText: `${time}s后重新发送`,
}); })
if (time <= 0) { if (time <= 0) {
clearInterval(timer as number); clearInterval(timer as number)
timer = null; timer = null
this.setData({ this.setData({
codeText: "发送验证码", codeText: '发送验证码',
}); })
} }
}, 1000); }, 1000)
}); })
}, },
handleSubmit() { handleSubmit() {
const { mobile, code } = this.data; const { mobile, code } = this.data
const { registrationSource, registChannel, regBusinessId } = app.globalData; const { registrationSource, registChannel, regBusinessId } = app.globalData
wx.ajax({ wx.ajax({
method: "POST", method: 'POST',
url: "?r=zd/account/update-telephone", url: '?r=zd/account/update-telephone',
data: { data: {
mobile, mobile,
code, code,
@ -69,10 +70,10 @@ Page({
regBusinessId, regBusinessId,
}, },
}).then((_res) => { }).then((_res) => {
wx.navigateBack(); wx.navigateBack()
}); })
}, },
handleBack() { handleBack() {
wx.navigateBack(); wx.navigateBack()
}, },
}); })

89
src/patient/pages/changeUser/index.ts

@ -1,66 +1,67 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
let timer = null as null | number; let timer = null as null | number
Page({ Page({
data: { data: {
mobile: "", mobile: '',
code: "", code: '',
codeText: "发送验证码", codeText: '发送验证码',
}, },
onLoad() {}, onLoad() {},
getCode() { getCode() {
if (timer) return; if (timer)
const mobile = this.data.mobile; return
const mobile = this.data.mobile
if (!mobile) { if (!mobile) {
wx.showToast({ wx.showToast({
title: "手机号不能为空", title: '手机号不能为空',
icon: "none", icon: 'none',
}); })
return; return
} }
// 验证手机号 // 验证手机号
if (!/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(mobile)) { if (!/^(13\d|14[579]|15[0-3,5-9]|166|17[0135-8]|18\d|19[89])\d{8}$/.test(mobile)) {
wx.showToast({ wx.showToast({
title: "手机号格式不正确", title: '手机号格式不正确',
icon: "none", icon: 'none',
}); })
return; return
} }
wx.ajax({ wx.ajax({
method: "POST", method: 'POST',
url: "?r=zd/login/send-verify-code", url: '?r=zd/login/send-verify-code',
data: { data: {
mobile, mobile,
}, },
}).then((res) => { }).then((res) => {
console.log(res); console.log(res)
wx.showToast({ wx.showToast({
icon: "none", icon: 'none',
title: "验证码已发送~", title: '验证码已发送~',
}); })
let time = 60; let time = 60
timer = setInterval(() => { timer = setInterval(() => {
time--; time--
this.setData({ this.setData({
codeText: time + "s后重新发送", codeText: `${time}s后重新发送`,
}); })
if (time <= 0) { if (time <= 0) {
clearInterval(timer as number); clearInterval(timer as number)
timer = null; timer = null
this.setData({ this.setData({
codeText: "发送验证码", codeText: '发送验证码',
}); })
} }
}, 1000); }, 1000)
}); })
}, },
handleSubmit() { handleSubmit() {
const { mobile, code } = this.data; const { mobile, code } = this.data
const { registrationSource, registChannel, regBusinessId } = app.globalData; const { registrationSource, registChannel, regBusinessId } = app.globalData
wx.ajax({ wx.ajax({
method: "POST", method: 'POST',
url: "?r=zd/login/change-user-login", url: '?r=zd/login/change-user-login',
data: { data: {
mobile, mobile,
code, code,
@ -70,20 +71,20 @@ Page({
}, },
}) })
.then((res) => { .then((res) => {
console.log(res); console.log(res)
wx.reLaunch({ wx.reLaunch({
url: "/patient/pages/index/index", url: '/patient/pages/index/index',
}); })
}) })
.catch((err) => { .catch((err) => {
wx.showToast({ wx.showToast({
title: err.data.msg, title: err.data.msg,
icon: "none", icon: 'none',
duration: 3000, duration: 3000,
}); })
}); })
}, },
handleBack() { handleBack() {
wx.navigateBack(); wx.navigateBack()
}, },
}); })

6
src/patient/pages/comIns/index.ts

@ -1,12 +1,12 @@
const _app = getApp<IAppOption>(); const _app = getApp<IAppOption>()
Page({ Page({
data: { data: {
toastShow: true, toastShow: true,
// toastType: "aldAlert", // toastType: "aldAlert",
// toastType: "aldAlertTest", // toastType: "aldAlertTest",
toastType: "vipScan", toastType: 'vipScan',
toastParams: {}, toastParams: {},
}, },
onLoad() {}, onLoad() {},
}); })

2
src/patient/pages/doctor/index.json

@ -8,6 +8,6 @@
"timeOut": "/components/timeOut/index", "timeOut": "/components/timeOut/index",
"toast": "/components/toast/index", "toast": "/components/toast/index",
"siteShare": "./siteShare/index", "siteShare": "./siteShare/index",
"pickerArea":"/components/pickerArea/index" "pickerArea": "/components/pickerArea/index"
} }
} }

4
src/patient/pages/doctor/siteShare/index.ts

@ -215,7 +215,6 @@ Component({
}, },
methods: { methods: {
handleShow() { handleShow() {
this.setData({ this.setData({
show: true, show: true,
ProvinceName: this.data.pname || '', ProvinceName: this.data.pname || '',
@ -277,7 +276,8 @@ Component({
}, },
getRangeList() { getRangeList() {
const { area, ProvinceId } = this.data const { area, ProvinceId } = this.data
if (!ProvinceId) return if (!ProvinceId)
return
const range = area.filter((item: any) => item.value == ProvinceId)[0].children const range = area.filter((item: any) => item.value == ProvinceId)[0].children
this.setData({ this.setData({
range, range,

6
src/patient/pages/drugRecord/index.scss

@ -30,7 +30,7 @@
position: absolute; position: absolute;
left: 0; left: 0;
top: 16rpx; top: 16rpx;
content: ""; content: '';
width: 153rpx; width: 153rpx;
height: 0rpx; height: 0rpx;
border: 2rpx solid #dddddd; border: 2rpx solid #dddddd;
@ -39,7 +39,7 @@
position: absolute; position: absolute;
right: 0; right: 0;
top: 16rpx; top: 16rpx;
content: ""; content: '';
width: 153rpx; width: 153rpx;
height: 0rpx; height: 0rpx;
border: 2rpx solid #dddddd; border: 2rpx solid #dddddd;
@ -140,7 +140,7 @@
text-align: center; text-align: center;
line-height: 88rpx; line-height: 88rpx;
font-size: 34rpx; font-size: 34rpx;
color: #FFFFFF; color: #ffffff;
font-weight: bold; font-weight: bold;
} }
} }

3
src/patient/pages/drugRecord/index.ts

@ -96,7 +96,8 @@ Page({
}, },
}) })
wx.removeStorageSync('adlResultInfo') wx.removeStorageSync('adlResultInfo')
} else { }
else {
wx.showToast({ wx.showToast({
title: '提交成功', title: '提交成功',
icon: 'none', icon: 'none',

1
src/patient/pages/family/index.ts

@ -19,7 +19,6 @@ Page({
}, },
onLoad() { onLoad() {
app.zdWaitLogin().then(() => { app.zdWaitLogin().then(() => {
this.getMpInfo() this.getMpInfo()
}) })
}, },

2
src/patient/pages/familyList/index.json

@ -4,6 +4,6 @@
"usingComponents": { "usingComponents": {
"navBar": "/components/zd-navBar/navBar", "navBar": "/components/zd-navBar/navBar",
"van-icon": "@vant/weapp/icon/index", "van-icon": "@vant/weapp/icon/index",
"toast":"/components/toast/index" "toast": "/components/toast/index"
} }
} }

61
src/patient/pages/familyList/index.ts

@ -1,79 +1,78 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
Page({ Page({
data: { data: {
toastShow: false, toastShow: false,
toastType: "", toastType: '',
// toastShow:true, // toastShow:true,
// toastType:"familyUnbind", // toastType:"familyUnbind",
familyList: [], familyList: [],
zdUserInfo: {}, zdUserInfo: {},
UserId: "", UserId: '',
}, },
onLoad() { onLoad() {
app.zdWaitLogin().then(() => { app.zdWaitLogin().then(() => {
this.getFamilyList()
this.getFamilyList(); app.getZdUserInfo(this)
app.getZdUserInfo(this); })
});
}, },
getFamilyList(loading = true) { getFamilyList(loading = true) {
wx.ajax({ wx.ajax({
method: "GET", method: 'GET',
url: "?r=zd/account/relatives", url: '?r=zd/account/relatives',
data: {}, data: {},
loading, loading,
}).then((res) => { }).then((res) => {
this.setData({ this.setData({
familyList: res, familyList: res,
}); })
}); })
}, },
handleUnbind(e) { handleUnbind(e) {
const { id } = e.currentTarget.dataset; const { id } = e.currentTarget.dataset
this.setData({ this.setData({
UserId: id, UserId: id,
toastShow: true, toastShow: true,
toastType: "familyUnbind", toastType: 'familyUnbind',
}); })
}, },
handleUnbinOk() { handleUnbinOk() {
const { UserId } = this.data; const { UserId } = this.data
this.handleUnbindCancel(); this.handleUnbindCancel()
wx.ajax({ wx.ajax({
method: "POST", method: 'POST',
url: "?r=zd/account/unbind-user", url: '?r=zd/account/unbind-user',
data: { data: {
UserId, UserId,
}, },
loading: true, loading: true,
}).then(() => { }).then(() => {
wx.showToast({ wx.showToast({
icon: "none", icon: 'none',
title: "解绑成功", title: '解绑成功',
success: () => { success: () => {
app.getZdUserInfo(this, true, (_zdUserInfo) => { app.getZdUserInfo(this, true, (_zdUserInfo) => {
app.zdWaitLogin().then(() => { app.zdWaitLogin().then(() => {
this.getFamilyList(false); this.getFamilyList(false)
}); })
}); })
}, },
}); })
}); })
}, },
handleUnbindCancel() { handleUnbindCancel() {
this.setData({ this.setData({
toastShow: false, toastShow: false,
toastType: "", toastType: '',
}); })
}, },
handleBack() { handleBack() {
wx.navigateBack({ wx.navigateBack({
fail() { fail() {
wx.reLaunch({ wx.reLaunch({
url: "/patient/pages/index/index", url: '/patient/pages/index/index',
}); })
}, },
}); })
}, },
}); })

12
src/patient/pages/familyScan/index.scss

@ -74,7 +74,7 @@
.tip { .tip {
font-size: 36rpx; font-size: 36rpx;
font-weight: bold; font-weight: bold;
color: #E04775; color: #e04775;
} }
.content { .content {
margin-top: 30rpx; margin-top: 30rpx;
@ -88,7 +88,7 @@
.sure { .sure {
margin-top: 60rpx; margin-top: 60rpx;
font-size: 36rpx; font-size: 36rpx;
color: #E04775; color: #e04775;
font-weight: bold; font-weight: bold;
} }
} }
@ -131,7 +131,7 @@
} }
.active { .active {
.name { .name {
color: #E04775; color: #e04775;
} }
.icon { .icon {
display: none; display: none;
@ -158,13 +158,13 @@
text-align: center; text-align: center;
border-radius: 12rpx; border-radius: 12rpx;
font-size: 28rpx; font-size: 28rpx;
color: #E04775; color: #e04775;
font-weight: bold; font-weight: bold;
background-color: #f9f7fa; background-color: #f9f7fa;
} }
.active { .active {
color: #fff; color: #fff;
background-color: #E04775; background-color: #e04775;
} }
} }
} }
@ -203,7 +203,7 @@
.submit { .submit {
color: #fff; color: #fff;
background-color: #E04775; background-color: #e04775;
} }
} }
} }

74
src/patient/pages/familyScan/index.ts

@ -1,10 +1,9 @@
const app = getApp<IAppOption>(); const app = getApp<IAppOption>()
import { parseScene } from "@/utils/util";
Page({ Page({
data: { data: {
PatientId: "", PatientId: '',
RelationType: "", RelationType: '',
resetBind: false, resetBind: false,
reload: false, reload: false,
mpPatientInfo: {}, mpPatientInfo: {},
@ -14,77 +13,78 @@ Page({
onLoad(options) { onLoad(options) {
this.setData({ this.setData({
ignoreAgreement: options.ignoreAgreement, ignoreAgreement: options.ignoreAgreement,
}); })
}, },
onShow() { onShow() {
// const options = wx.getEnterOptionsSync(); // const options = wx.getEnterOptionsSync();
const scene = app.globalData.scene; const scene = app.globalData.scene
if (scene?.pId) { if (scene?.pId) {
this.setData({ this.setData({
PatientId: scene.pId, PatientId: scene.pId,
}); })
} }
app.zdWaitLogin({ isReg: false }).then(() => { app.zdWaitLogin({ isReg: false }).then(() => {
app.getZdUserInfo(this, true, () => { app.getZdUserInfo(this, true, () => {
this.getMpPatientInfo(); this.getMpPatientInfo()
}); })
}); })
}, },
getMpPatientInfo() { getMpPatientInfo() {
const { UserType } = this.data.zdUserInfo; const { UserType } = this.data.zdUserInfo
wx.ajax({ wx.ajax({
method: "GET", method: 'GET',
url: "?r=zd/account/mp-patient-info", url: '?r=zd/account/mp-patient-info',
data: { data: {
PatientId: this.data.PatientId, PatientId: this.data.PatientId,
}, },
loading: true, loading: true,
}).then((res) => { }).then((res) => {
let RelationType = res.HasSelf == 1 ? "2" : ""; const RelationType = res.HasSelf == 1 ? '2' : ''
if (!res.PatientId) { if (!res.PatientId) {
if (!this.data.ignoreAgreement) { if (!this.data.ignoreAgreement) {
if (UserType >= 2) { if (UserType >= 2) {
wx.navigateTo({ wx.navigateTo({
url: `/patient/pages/privacyAgreement/index?page=/patient/pages/familyScan/index`, url: `/patient/pages/privacyAgreement/index?page=/patient/pages/familyScan/index`,
}); })
} else { }
else {
wx.navigateTo({ wx.navigateTo({
url: `/patient/pages/login/index?page=/patient/pages/familyScan/index`, url: `/patient/pages/login/index?page=/patient/pages/familyScan/index`,
}); })
} }
} }
} }
this.setData({ this.setData({
mpPatientInfo: res, mpPatientInfo: res,
RelationType: res.HasSelf ? "2" : RelationType, RelationType: res.HasSelf ? '2' : RelationType,
reload: true, reload: true,
}); })
}); })
}, },
handleHome() { handleHome() {
wx.reLaunch({ wx.reLaunch({
url: "/patient/pages/index/index", url: '/patient/pages/index/index',
}); })
}, },
handleResetBind() { handleResetBind() {
this.setData({ this.setData({
resetBind: true, resetBind: true,
}); })
}, },
handleSwitchRType(e) { handleSwitchRType(e) {
const { type } = e.currentTarget.dataset; const { type } = e.currentTarget.dataset
this.setData({ this.setData({
RelationType: type, RelationType: type,
}); })
}, },
handleSubmit() { handleSubmit() {
const { PatientId, RelationType } = this.data; const { PatientId, RelationType } = this.data
if (!RelationType) { if (!RelationType) {
wx.showToast({ wx.showToast({
title: "请选择身份", title: '请选择身份',
icon: "none", icon: 'none',
}); })
return; return
} }
// wx.reLaunch({ // wx.reLaunch({
@ -93,8 +93,8 @@ Page({
// return; // return;
wx.ajax({ wx.ajax({
method: "POST", method: 'POST',
url: "?r=zd/account/bind-patient", url: '?r=zd/account/bind-patient',
data: { data: {
PatientId, PatientId,
RelationType, RelationType,
@ -103,9 +103,9 @@ Page({
}).then(() => { }).then(() => {
app.getZdUserInfo(this, true, (zdUserInfo) => { app.getZdUserInfo(this, true, (zdUserInfo) => {
wx.reLaunch({ wx.reLaunch({
url: "/patient/pages/index/index", url: '/patient/pages/index/index',
}); })
}); })
}); })
}, },
}); })

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

Loading…
Cancel
Save