dependency: migrate from moment to dayjs

This commit is contained in:
Jesse Chan
2020-09-17 23:29:35 +08:00
parent 41c270e6a1
commit 30d2b034b3
8 changed files with 83 additions and 83 deletions

View File

@@ -1,5 +1,4 @@
import {defineMessages, FormattedMessage, injectIntl, WrappedComponentProps} from 'react-intl';
import formatUtil from '@shared/util/formatUtil';
import React from 'react';
import throttle from 'lodash/throttle';
@@ -18,6 +17,7 @@ import {
import Edit from '../../icons/Edit';
import Close from '../../icons/Close';
import FeedsStore, {FeedsStoreClass} from '../../../stores/FeedsStore';
import {minToHumanReadable} from '../../../i18n/languages';
import ModalFormSectionHeader from '../ModalFormSectionHeader';
import * as validators from '../../../util/validators';
import UIActions from '../../../actions/UIActions';
@@ -284,7 +284,7 @@ class FeedsTab extends React.Component<FeedsTabProps, FeedsTabStates> {
<li
className="interactive-list__detail-list__item
interactive-list__detail interactive-list__detail--tertiary">
{formatUtil.minToHumanReadable(feed.interval)}
{minToHumanReadable(feed.interval)}
</li>
<li
className="interactive-list__detail-list__item

View File

@@ -1,7 +1,8 @@
import classnames from 'classnames';
import {defineMessages, injectIntl, WrappedComponentProps} from 'react-intl';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import formatUtil from '@shared/util/formatUtil';
import moment from 'moment';
import React from 'react';
import ClientStatusStore from '../../stores/ClientStatusStore';
@@ -69,9 +70,9 @@ class TransferRateDetails extends React.Component<TransferRateDetailsProps> {
});
if (inspectorPoint != null && inspectorPoint.nearestTimestamp != null) {
const currentTime = moment(Date.now());
const currentTime = dayjs(Date.now());
const durationSummary = formatUtil.secondsToDuration(
moment.duration(currentTime.diff(moment(inspectorPoint.nearestTimestamp))).asSeconds(),
dayjs.duration(currentTime.diff(dayjs(inspectorPoint.nearestTimestamp))).asSeconds(),
);
timestamp = (
@@ -118,6 +119,8 @@ class TransferRateDetails extends React.Component<TransferRateDetailsProps> {
}
}
dayjs.extend(duration);
const ConnectedTransferRateDetails = connectStores<Omit<TransferRateDetailsProps, 'intl'>, Record<string, unknown>>(
injectIntl(TransferRateDetails),
() => {

View File

@@ -1,5 +1,9 @@
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import {IntlProvider} from 'react-intl';
import React from 'react';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/en';
import type {MessageFormatElement} from 'intl-messageformat-parser';
@@ -7,6 +11,8 @@ import detectLocale from '../util/detectLocale';
import EN from './strings.compiled.json';
import Languages from '../constants/Languages';
let dayjsLocale: Exclude<keyof typeof Languages, 'auto' | 'zh-Hans' | 'zh-Hant'> | 'zh-cn' | 'zh-tw' = 'en';
const messagesCache: Partial<Record<
Exclude<keyof typeof Languages, 'auto'>,
Record<string, MessageFormatElement[]>
@@ -15,13 +21,25 @@ const messagesCache: Partial<Record<
async function loadMessages(locale: Exclude<keyof typeof Languages, 'auto' | 'en'>) {
const messages: Record<string, MessageFormatElement[]> = await import(`./compiled/${locale}.json`);
messagesCache[locale] = messages;
await import(`dayjs/locale/${dayjsLocale}.js`);
return messages;
}
function getMessages(locale: Exclude<keyof typeof Languages, 'auto'>) {
if (locale === 'zh-Hans') {
dayjsLocale = 'zh-cn';
} else if (locale === 'zh-Hant') {
dayjsLocale = 'zh-tw';
} else {
dayjsLocale = locale;
}
if (messagesCache[locale]) {
return messagesCache[locale];
}
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw loadMessages(locale as Exclude<keyof typeof Languages, 'auto' | 'en'>);
}
@@ -42,4 +60,25 @@ const AsyncIntlProvider = ({locale, children}: {locale?: keyof typeof Languages;
);
};
dayjs.extend(duration);
dayjs.extend(relativeTime);
export const minToHumanReadable = (min: number) => {
try {
return dayjs
.duration(min * 60 * 1000)
.locale(dayjsLocale)
.humanize(false);
} catch {
try {
return dayjs
.duration(min * 60 * 1000)
.locale('en')
.humanize(false);
} catch {
return `${min}`;
}
}
};
export default AsyncIntlProvider;

View File

@@ -40,4 +40,4 @@ function detectLocale(): Exclude<keyof typeof Languages, 'auto'> {
return detectedLocale;
}
export default detectLocale;
export default detectLocale;

10
package-lock.json generated
View File

@@ -6588,6 +6588,11 @@
}
}
},
"dayjs": {
"version": "1.8.36",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.8.36.tgz",
"integrity": "sha512-3VmRXEtw7RZKAf+4Tv1Ym9AGeo8r8+CjDi26x+7SYQil1UqtqdaokhzoEJohqlzt0m5kacJSDhJQkG/LWhpRBw=="
},
"debug": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
@@ -12326,11 +12331,6 @@
"integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
"dev": true
},
"moment": {
"version": "2.28.0",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.28.0.tgz",
"integrity": "sha512-Z5KOjYmnHyd/ukynmFd/WwyXHd7L4J9vTI/nn5Ap9AVUgaAE15VvQ9MOGmJJygEUklupqIrFnor/tjTwRU+tQw=="
},
"morgan": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz",

View File

@@ -40,6 +40,7 @@
"chalk": "^4.1.0",
"compression": "^1.7.3",
"cookie-parser": "^1.4.5",
"dayjs": "^1.8.36",
"debug": "^4.1.1",
"deep-equal": "^2.0.3",
"express": "^4.17.1",
@@ -51,7 +52,6 @@
"joi": "^17.2.1",
"jsonwebtoken": "^8.4.0",
"lodash": "^4.17.20",
"moment": "^2.28.0",
"morgan": "^1.10.0",
"multer": "^1.4.2",
"mv": "^2.1.1",

View File

@@ -1,71 +0,0 @@
const moment = require('moment');
const formatUtil = {
secondsToDuration: (cumSeconds) => {
const years = Math.floor(cumSeconds / 31536000);
const weeks = Math.floor((cumSeconds % 31536000) / 604800);
const days = Math.floor(((cumSeconds % 31536000) % 604800) / 86400);
const hours = Math.floor((((cumSeconds % 31536000) % 604800) % 86400) / 3600);
const minutes = Math.floor(((((cumSeconds % 31536000) % 604800) % 86400) % 3600) / 60);
const seconds = Math.floor(cumSeconds - minutes * 60);
let timeRemaining = null;
if (years > 0) {
timeRemaining = {years, weeks, cumSeconds};
} else if (weeks > 0) {
timeRemaining = {weeks, days, cumSeconds};
} else if (days > 0) {
timeRemaining = {days, hours, cumSeconds};
} else if (hours > 0) {
timeRemaining = {hours, minutes, cumSeconds};
} else if (minutes > 0) {
timeRemaining = {minutes, seconds, cumSeconds};
} else {
timeRemaining = {seconds, cumSeconds};
}
return timeRemaining;
},
minToHumanReadable: (min) => moment.duration(min * 60 * 1000).humanize(),
parsePeers: (string) => {
// This lovely delimiter is defined in clientResponseUtil.
const markerPosition = string.indexOf('@!@');
return string.substr(0, markerPosition);
},
status: (isHashing, isComplete, isOpen, uploadRate, downloadRate, state, message) => {
const torrentStatus = [];
if (isHashing !== '0') {
torrentStatus.push('ch'); // checking
} else if (isComplete === '1' && isOpen === '1' && state === '1') {
torrentStatus.push('sd'); // seeding
} else if (isComplete === '1' && isOpen === '1' && state === '0') {
torrentStatus.push('p'); // paused
} else if (isComplete === '1' && isOpen === '0') {
torrentStatus.push('c'); // complete
} else if (isComplete === '0' && isOpen === '1' && state === '1') {
torrentStatus.push('d'); // downloading
} else if (isComplete === '0' && isOpen === '1' && state === '0') {
torrentStatus.push('p'); // paused
} else if (isComplete === '0' && isOpen === '0') {
torrentStatus.push('s'); // stopped
}
if (message.length) {
torrentStatus.push('e'); // error
}
if (uploadRate === '0' && downloadRate === '0') {
torrentStatus.push('i');
} else {
torrentStatus.push('a');
}
return torrentStatus;
},
};
module.exports = formatUtil;

29
shared/util/formatUtil.ts Normal file
View File

@@ -0,0 +1,29 @@
const formatUtil = {
secondsToDuration: (cumSeconds: number) => {
const years = Math.floor(cumSeconds / 31536000);
const weeks = Math.floor((cumSeconds % 31536000) / 604800);
const days = Math.floor(((cumSeconds % 31536000) % 604800) / 86400);
const hours = Math.floor((((cumSeconds % 31536000) % 604800) % 86400) / 3600);
const minutes = Math.floor(((((cumSeconds % 31536000) % 604800) % 86400) % 3600) / 60);
const seconds = Math.floor(cumSeconds - minutes * 60);
let timeRemaining = null;
if (years > 0) {
timeRemaining = {years, weeks, cumSeconds};
} else if (weeks > 0) {
timeRemaining = {weeks, days, cumSeconds};
} else if (days > 0) {
timeRemaining = {days, hours, cumSeconds};
} else if (hours > 0) {
timeRemaining = {hours, minutes, cumSeconds};
} else if (minutes > 0) {
timeRemaining = {minutes, seconds, cumSeconds};
} else {
timeRemaining = {seconds, cumSeconds};
}
return timeRemaining;
},
};
export default formatUtil;