首页 > 其他分享 >react + antd + js 简单Cron组件,支持国际化

react + antd + js 简单Cron组件,支持国际化

时间:2024-05-09 18:05:48浏览次数:20  
标签:react const oldObj value newObj Cron && freq js

Cron.js

import React, { Fragment, useState, useCallback, useRef, useEffect } from 'react';
import { Select, TimePicker, Input } from 'antd';

const Option = Select.Option;
const mwidth80 = { minWidth: 80, marginRight: 10 };
const width150 = { width: 150 };
const eachNum = (start, end, str) => {
  const back = [];
  for (let i = start; i <= end; i++) {
    back.push({
      value: `${i}`,
      label: `${i} ${str}`,
    });
  }
  return back;
};

const zhCNLanguage = {
  dayOfWeekList: [
    { label: '周一', value: 'MON' },
    { label: '周二', value: 'TUE' },
    { label: '周三', value: 'WED' },
    { label: '周四', value: 'THU' },
    { label: '周五', value: 'FRI' },
    { label: '周六', value: 'SAT' },
    { label: '周日', value: 'SUN' },
  ],
  minuteOfHoursList: eachNum(0, 59, '分'),
  dayOfMonthList: [
    ...eachNum(1, 31, '号'),
    {
      label: '月末',
      value: 'L',
      exclusive: true,
    },
  ],
  monthOfYearList: eachNum(1, 12, '月'),
  freqList: [
    { value: 'everyHours', label: '每小时' },
    { value: 'everyday', label: '每天' },
    { value: 'week', label: '每周' },
    { value: 'month', label: '每月' },
    // { value: 'year', label: '每年' },
    { value: 'custom', label: '自定义' },
  ],
  date:'日期',
  month:'月份',
  week:'星期',
  minute:'分钟',
}

const enUSLanguage = {
  dayOfWeekList: [
    { label: 'Monday', value: 'MON' },
    { label: 'Tuesday', value: 'TUE' },
    { label: 'Wednesday', value: 'WED' },
    { label: 'Thursday', value: 'THU' },
    { label: 'Friday', value: 'FRI' },
    { label: 'Saturday', value: 'SAT' },
    { label: 'Sunday', value: 'SUN' },
  ],
  minuteOfHoursList: eachNum(0, 59, 'Branch'),
  dayOfMonthList: [
    ...eachNum(1, 31, 'Day'),
    {
      label: 'at the end of the month',
      value: 'L',
      exclusive: true,
    },
  ],
  monthOfYearList: eachNum(1, 12, 'Month'),
  freqList: [
    { value: 'everyHours', label: 'every hour' },
    { value: 'everyday', label: 'every day' },
    { value: 'week', label: 'weekly' },
    { value: 'month', label: 'monthly' },
    // { value: 'year', label: '每年' },
    { value: 'custom', label: 'custom' },
  ],
  date:'date',
  month:'month',
  week:'week',
  minute:'minute',
}


let labelObj = zhCNLanguage;
const exclusiveDays = labelObj.dayOfMonthList.filter((d) => d.exclusive).map((d) => d.value);
const checkIncludeExclusive = (dd) => {
  return !!(dd || []).find((d) => exclusiveDays.includes(d));
};
const cornFormat = (corn, mode) => {
  const value = corn || '0 0 0 * * ?';
  const cronElements = value.split(' ');
  let [ss, mm, HH, dd, MM, week, yyyy] = cronElements;
  let freq;
  if (yyyy !== '*' || /[-\/#]/.test(value) || (!mode && /[,]/.test(value))) {
    freq = 'custom';
  } else if (week !== '?') {
    freq = 'week';
  } else if (MM === '*' && dd === '*' && HH === '*' && mm !== '*' && ss === '0') {
    freq = 'everyHours';
  } else if (MM === '*' && dd === '*') {
    freq = 'everyday';
  } else if (MM === '*') {
    freq = 'month';
  } else if (MM !== '*') {
    freq = 'year';
  }

  return {
    freq,
    stringValue: value,
    ss: parseInt(ss) || 0,
    mm: freq === 'everyHours' && !!mode ? mm.split(',').filter((i) => !!i) : parseInt(mm) || 0,
    HH: parseInt(HH) || 0,
    dd: dd.split(',').filter((i) => !!i),
    MM: MM.split(',').filter((i) => !!i),
    week: week.split(',').filter((i) => !!i),
    yyyy,
  };
};
const cornStringify = ({ freq, stringValue, ss, mm, HH, dd, MM, week, yyyy }) => {
  if (freq === 'custom') {
    return stringValue;
  } else if (freq === 'year') {
    week = '?';
    if (!dd || dd.length <= 0) {
      dd = '*';
    }
  } else if (freq === 'month') {
    MM = '*';
    week = '?';
  } else if (freq === 'week') {
    MM = '*';
    dd = '?';
  } else if (freq === 'everyday') {
    MM = '*';
    week = '?';
    dd = '*';
  } else if (freq === 'everyHours') {
    MM = '*';
    week = '?';
    dd = '*';
    HH = '*';
    ss = '0';
  }

  return `${ss} ${mm} ${HH} ${dd} ${MM} ${week}`;
};

export default function CronForm({ defaultValue, value, onChange, multiple, disabled, language }) {

  if(language === 'en'){
    labelObj = enUSLanguage;
  }
  const [objValue, setObjValue] = useState({});
  const thisCron = useRef('');
  const changeValue = useCallback((newObj) => {
    const cronString = cornStringify(newObj);
    thisCron.current = cronString;
    onChange && onChange(cronString);
  });
  const onFreqChanged = useCallback((freq) => {
    setObjValue((oldObj) => {
      const newObj = {
        ...oldObj,
        freq,
        week: freq === 'week' ? ['MON'] : [],
        dd: freq === 'month' ? ['1'] : [],
        mm: Array.isArray(oldObj.mm) ? 0 : oldObj.mm,
        ...(freq === 'everyHours' && multiple
          ? {
            mm: ['0'],
          }
          : {}),
        MM: freq === 'year' ? ['1'] : '*',
        ...(freq === 'custom'
          ? {
            stringValue: cornStringify(oldObj),
          }
          : {}),
      };
      changeValue(newObj);
      return newObj;
    });
  }, []);
  const onMonthOfYearChanged = useCallback((MM) => {
    setObjValue((oldObj) => {
      const newObj = {
        ...oldObj,
        MM,
      };
      changeValue(newObj);
      return newObj;
    });
  }, []);
  const onDayOfWeekChanged = useCallback((week) => {
    setObjValue((oldObj) => {
      const newObj = {
        ...oldObj,
        week,
      };
      changeValue(newObj);
      return newObj;
    });
  }, []);
  const onDayOfMonthChanged = useCallback((dd) => {
    setObjValue((oldObj) => {
      const newObj = {
        ...oldObj,
        dd,
      };
      changeValue(newObj);
      return newObj;
    });
  }, []);
  const onFreqTimeChanged = useCallback((time) => {
    setObjValue((oldObj) => {
      const newTime = time
        ? { ss: time.second(), mm: time.minute(), HH: time.hour() }
        : { ss: 0, mm: 0, HH: 0 };
      const newObj = {
        ...oldObj,
        ...newTime,
      };
      changeValue(newObj);
      return newObj;
    });
  }, []);
  const onMinuteOfHoursListChanged = useCallback((mm) => {
    setObjValue((oldObj) => {
      const newObj = {
        ...oldObj,
        mm,
      };
      changeValue(newObj);
      return newObj;
    });
  }, []);
  const onStringValueChanged = useCallback((e) => {
    e.persist();
    setObjValue((oldObj) => {
      const newObj = {
        ...oldObj,
        stringValue: e.target.value,
      };
      changeValue(newObj);
      return newObj;
    });
  }, []);
  useEffect(() => {
    thisCron.current = value;
    const objValue = cornFormat(value || defaultValue, multiple);
    setObjValue(objValue);
    // 默认按天调度
    if (!value && !defaultValue) {
      changeValue(objValue);
    }
  }, []);
  useEffect(() => {
    if (thisCron.current !== value) {
      thisCron.current = value;
      setObjValue(cornFormat(value, multiple));
    }
  }, [value]);
  const { freq, stringValue, ss, mm, HH, dd = [], MM, week = [] } = objValue;
  const mode = multiple ? 'multiple' : undefined;
  const isYear = freq === 'year',
    isMonth = freq === 'month',
    isWeek = freq === 'week',
    isHours = freq === 'everyHours',
    isCustom = freq === 'custom';
  const isIncludeExclusive = mode && checkIncludeExclusive(dd);
  return (
    <Fragment>
      <Select value={freq} onChange={onFreqChanged} style={mwidth80} disabled={disabled}>
        {labelObj.freqList.map(({ value, label }) => (
          <Option key={value} value={value}>
            {label}
          </Option>
        ))}
      </Select>

      {isYear && (
        <Select
          value={MM}
          onChange={onMonthOfYearChanged}
          mode={mode}
          style={mwidth80}
          placeholder={labelObj.month}
          disabled={disabled}
        >
          {labelObj.monthOfYearList.map(({ value, label }) => (
            <Option key={value} value={value}>
              {label}
            </Option>
          ))}
        </Select>
      )}

      {(isYear || isMonth) && (
        <Select
          value={dd}
          onChange={onDayOfMonthChanged}
          mode={mode}
          style={mwidth80}
          placeholder={labelObj.date}
          allowClear={isYear}
          disabled={disabled}
        >
          {labelObj.dayOfMonthList.map(({ value, label, exclusive }) => (
            <Option
              key={value}
              value={value}
              disabled={
                mode && dd && dd.length > 0 && isIncludeExclusive === !exclusive
              }
            >
              {label}
            </Option>
          ))}
        </Select>
      )}

      {isWeek && (
        <Select
          value={week}
          onChange={onDayOfWeekChanged}
          mode={mode}
          style={mwidth80}
          placeholder={labelObj.week}
          disabled={disabled}
        >
          {labelObj.dayOfWeekList.map(({ value, label }) => (
            <Option key={value} value={value}>
              {label}
            </Option>
          ))}
        </Select>
      )}

      {isHours && (
        <Select
          value={mm}
          onChange={onMinuteOfHoursListChanged}
          mode={mode}
          style={mwidth80}
          placeholder={labelObj.minute}
          disabled={disabled}
        >
          {labelObj.minuteOfHoursList.map(({ value, label }) => (
            <Option key={value} value={value}>
              {label}
            </Option>
          ))}
        </Select>
      )}

      {!isHours && !isCustom && (
        <TimePicker
          // defaultOpenValue={dayjs('00:00:00', 'HH:mm:ss')}
          onChange={onFreqTimeChanged}
          disabled={disabled}
        />
      )}

      {isCustom && (
        <Input
          style={width150}
          value={stringValue}
          onChange={onStringValueChanged}
          disabled={disabled}
        />
      )}
    </Fragment>
  );
}

使用

 <Corn
                  value={cronValue}
                  multiple={true}
                  language={getLocale() === 'zh-CN' ? 'cn' : 'en'}
                  onChange={(v: any) => {
                    console.log("当前选中时间",v)
                    setCronValue(v);
                  }}
                />

 

标签:react,const,oldObj,value,newObj,Cron,&&,freq,js
From: https://www.cnblogs.com/fhysy/p/18182824

相关文章

  • React文本溢出组件封装以及高亮提示
    React文本溢出组件封装以及高亮提示Abbr组件:使用场景:当我们需要设置支持最大行数时进行省略展示当我们需要设置支持设置超过多少字符进行省略展示当我们需要设置支持关键字高亮展示(有点问题,当关键字被裁剪成...之后,就无法高亮)当我们需要支持忽略大小写高亮当我们需要支持......
  • JS之金额转换为大写
    金额转换为大写函数如下:exportfunctionconvertToChineseCapital(n){if(n==0){return"零";}if(!/^(\+|-)?(0|[1-9]\d*)(\.\d+)?$/.test(n))return"数据非法";varunit="仟佰拾亿仟佰拾万仟佰拾元角分",str="";n+=&......
  • CSS JS 自适应菜单
      <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><title>ResponsiveMenu</t......
  • Error: Cannot find module ‘D:\SoftSetupLoaction\nodejs\node_global\node_mod
    Error:Cannotfindmodule‘D:\SoftSetupLoaction\nodejs\node_global\node_modules\npm\bin\npm-cli.js‘  出现原因:重新安装可装了nodejs和npm网上查了很多方法,都建议重装,但是都没有效果(因为我就是重装之后出现的问题)按照错误提示node_global找不到npm-cli.js,个......
  • Node.js证件OCR、身份证实名认证接口、身份证识别API
    身份证是证明公民身份的有效证件,一些不法分子可以通过简单的工序制作出假身份证,损害老百姓的合法利益。据警方统计,大部分预谋诈骗犯罪分子会使用假身份证件,而社会上也有一部分人出于不正当的目的,刻意隐瞒自己真实的身份信息。在这种前提下,“全国身份证联网核查”应运而生,它的......
  • Cysimdjson:地球上最快的 JSON 解析器
    处理简单的少量数据,对速度是无感的,但如果要处理大量数据,哪怕每次几十毫秒的差异,最终也会差异巨大。比如,你要为客户清洗一遍企业系统数据中,一堆之前留下的庞大的JSON文件。如果你打算用Python自带的JSON模块,那就调整好心态,备足咖啡,享受煎熬吧。但如果有人告诉你,有比Py......
  • three.js基础之小案例
     静态场景<canvasid="mainCanvas"></canvas><scripttype="importmap">{"imports":{"three":"./js/build/three.module.js","three/addons/":"./js/jsm/"......
  • P4407 [JSOI2009] 电子字典
    题目链接:https://www.luogu.com.cn/problem/P4407trie树+爆搜做法:对所有文本串建树。对于编辑距离要求的三种情况,分四类在trie树上爆搜即可。#definemaxn200010structtrie{intson[maxn][26];intcnt[maxn];intidx=0;map<string,bool>mm;intv......
  • python读写json文件
    1.新建json文件打开记事本,重命名为.json后缀使用的样例如下,注意看json文件格式:{"server":{"host":"example.com","port":443,"protocol":"https"},"authentication":{......
  • react 性能优化
    一纯组件1使用shouldComponentUpdate对先前的状态和props数据与下一个props或状态相同,如果两次的结果一直,那么就returnfalse使用纯净组件,pureComponentPureComponents负责shouldComponentUpdate——它对状态和props数据进行浅层比较(shallowcomparison),如果先前......