Skip to content

Commit

Permalink
Remove moment in favor of date-fns (keybase#22723)
Browse files Browse the repository at this point in the history
* feat: migrate away from moment

* fix: remove unused imports

* feat: use parseiso in log-to-trace

* feat: use date-fns for people page date formatting

* fix: clean up imports

* fix: add "ago" suffix and fix git test

* fix: remove moment dependency

* fix: remove unused variable

* fix: add more types

* fix: use correct local time parsing, day of month

* fix: use correct formatting for audio messages
  • Loading branch information
cori-hudson authored Feb 25, 2020
1 parent 837f62e commit 80d105a
Show file tree
Hide file tree
Showing 13 changed files with 157 additions and 203 deletions.
4 changes: 2 additions & 2 deletions shared/actions/__tests__/git.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const gitRepos = [
chatDisabled: false,
devicename: 'My Mac Device',
id: '1b091b39c3c248a0b97d09a4c46c9224_b3749db074a859d991c71bc28d99d82c',
lastEditTime: 'a minute ago',
lastEditTime: '1 minute ago',
lastEditUser: 'eifjls092',
name: 'meta',
repoID: 'b3749db074a859d991c71bc28d99d82c',
Expand All @@ -34,7 +34,7 @@ const gitRepos = [
chatDisabled: false,
devicename: 'My Mac Device',
id: '39ae3a19bf4215414d424677c37dce24_1a53ac017631bfbd59adfeb453c84c2c',
lastEditTime: 'a few seconds ago',
lastEditTime: 'less than a minute ago',
lastEditUser: 'eifjls092',
name: 'tea-shop',
repoID: '1a53ac017631bfbd59adfeb453c84c2c',
Expand Down
15 changes: 7 additions & 8 deletions shared/chat/conversation/list-area/index.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable sort-keys */
import * as React from 'react'
import * as Sb from '../../../stories/storybook'
import moment from 'moment'
import {Button, ButtonBar, Box2, Text} from '../../../common-adapters'
import * as Types from '../../../constants/types/chat2'
import {propProvider as ReactionsRowProvider} from '../messages/reactions-row/index.stories'
Expand All @@ -15,6 +14,7 @@ import HiddenString from '../../../util/hidden-string'
import JumpToRecent from './jump-to-recent'
import SpecialTopMessage from '../messages/special-top-message'
import * as Constants from '../../../constants/chat2'
import * as dateFns from 'date-fns'

const firstOrdinal = 10000
const makeMoreOrdinals = (
Expand Down Expand Up @@ -61,29 +61,28 @@ const words = ['At', 'Et', 'Itaque', 'Nam', 'Nemo', 'Quis', 'Sed', 'Temporibus',
// messagesThreshold number of consecutive messages with the same timestamp
const makeTimestampGen = (days: number = 7, threshold: number = 10) => {
const r = new Sb.Rnd(1337)
const origin = {year: 2018, month: 0, day: 0}

let messagesThreshold: number = 0
let generatedCount: number = 0
let currentTimestamp: number = 0

let dayRange: number = 0
const start = moment(origin)
const end = moment(origin)
let start = new Date(2018, 0, 0)
let end = new Date(2018, 0, 0)

return (): number => {
// Initialize or reset because threshold was crossed
if (currentTimestamp === 0 || generatedCount > messagesThreshold) {
// Move the start day up by the previous number of days to avoid overlap
start.add(dayRange, 'days')
start = dateFns.addDays(start, dayRange)
// Get a new date range for random timestamps
dayRange = (r.next() % days) + 1
end.add(dayRange, 'days')
end = dateFns.addDays(end, dayRange)

const diff = end.diff(start)
const diff = dateFns.differenceInMilliseconds(end, start)
// Multiply the epoch time different by some floating point between [0, 1]
const newDiff = diff * (r.next() / 2147483647)
const newTimestamp = moment(start.valueOf() + newDiff)
const newTimestamp = dateFns.getMilliseconds(dateFns.addMilliseconds(start, newDiff))
currentTimestamp = newTimestamp.valueOf()

// Reset threashold and count
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import moment from 'moment'
import * as React from 'react'
import * as Kb from '../../../../common-adapters'
import UserNotice from '../user-notice'
import * as RPCChatTypes from '../../../../constants/types/rpc-chat-gen'
import * as dateFns from 'date-fns'

type Props = {
canManage: boolean
Expand All @@ -27,15 +27,15 @@ const getPolicySummary = (props: Props) => {
return 'be retained indefinitely'
case RPCChatTypes.RetentionPolicyType.expire:
{
const expireDuration = moment.duration(props.policy.expire?.age, 'seconds').humanize()
const expireDuration = dateFns.formatDistanceStrict(0, props.policy.expire?.age * 1000)
if (expireDuration !== '') {
return `expire after ${expireDuration}`
}
}
break
case RPCChatTypes.RetentionPolicyType.ephemeral:
{
const ephemeralDuration = moment.duration(props.policy.ephemeral?.age, 'seconds').humanize()
const ephemeralDuration = dateFns.formatDistanceStrict(0, props.policy.ephemeral?.age * 1000)
if (ephemeralDuration !== '') {
return `explode after ${ephemeralDuration} by default`
}
Expand Down
4 changes: 2 additions & 2 deletions shared/constants/git.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as Types from './types/git'
import * as RPCTypes from './types/rpc-gen'
import moment from 'moment'
import {TypedState} from './reducer'
import * as dateFns from 'date-fns'

const emptyInfo = {
canDelete: false,
Expand Down Expand Up @@ -31,7 +31,7 @@ const parseRepoResult = (result: RPCTypes.GitRepoResult): Types.GitInfo | undefi
chatDisabled: !!r.teamRepoSettings && r.teamRepoSettings.chatDisabled,
devicename: r.serverMetadata.lastModifyingDeviceName,
id: r.globalUniqueID,
lastEditTime: moment(r.serverMetadata.mtime).fromNow(),
lastEditTime: dateFns.formatDistanceToNow(new Date(r.serverMetadata.mtime), {addSuffix: true}),
lastEditUser: r.serverMetadata.lastModifyingUsername,
name: r.localMetadata.repoName,
repoID: r.repoID,
Expand Down
22 changes: 12 additions & 10 deletions shared/desktop/yarn-helper/log-to-trace.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// A utility to convert our log sends to something consumable by chrome://tracing
import fs from 'fs'
import moment from 'moment'
import * as dateFns from 'date-fns'

type Args = {
counter?: string
Expand Down Expand Up @@ -175,15 +175,17 @@ const output: {
unmatched: [],
}

const buildEvent = (info: Info, ph: 'B' | 'E' | 'i'): Event => ({
args: info.args,
id: info.id,
name: info.name,
ph,
pid: 0,
tid: info.app,
ts: moment(info.time).valueOf() * (isGUI ? 1 : 1000),
})
const buildEvent = (info: Info, ph: 'B' | 'E' | 'i'): Event => {
return {
args: info.args,
id: info.id,
name: info.name,
ph,
pid: 0,
tid: info.app,
ts: dateFns.parseISO(info.time).getMilliseconds() * (isGUI ? 1 : 1000),
}
}

const buildGood = (old: Info, info: Info) => {
const s = buildEvent(old, 'B')
Expand Down
12 changes: 5 additions & 7 deletions shared/devices/index.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import * as React from 'react'
import moment from 'moment'
import * as Sb from '../stories/storybook'
import {stringToDeviceID} from '../constants/types/devices'
import DevicesReal from './container'
import devicePage from './device-page/index.stories'
import deviceRevoke from './device-revoke/index.stories'
import paperKey from './paper-key/index.stories'
import addDevice from './add-device/index.stories'
import * as dateFns from 'date-fns'

const idToType = i => {
switch (i) {
Expand All @@ -32,12 +32,10 @@ const activeDevices = withNew => {
return existingDevices
}

const secondAgo = moment()
.subtract(1, 'second')
.toDate()
const fourHoursAgo = moment()
.subtract(4, 'hours')
.toDate()
const now = new Date()
const secondAgo = dateFns.sub(now, {seconds: 1})

const fourHoursAgo = dateFns.sub(now, {hours: 4})

const revokedDevices = withNew => {
const existingDevices = [
Expand Down
3 changes: 1 addition & 2 deletions shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@
"base64-js": "1.3.1",
"buffer": "5.4.3",
"classnames": "2.2.6",
"date-fns": "2.9.0",
"emoji-datasource": "4.1.0",
"emoji-datasource-apple": "4.1.0",
"emoji-mart": "2.9.2",
Expand All @@ -155,7 +156,6 @@
"lottie-react-web": "git://github.com/keybase/lottie-react-web#nojima/keybase-fixes-off-214",
"memoize-one": "5.1.1",
"menubar": "6.0.8",
"moment": "2.24.0",
"mousetrap": "1.6.3",
"path-parse": "1.0.6",
"qrcode-generator": "git://github.com/keybase/qrcode-generator#keybase-changes-off-140",
Expand Down Expand Up @@ -230,7 +230,6 @@
"@types/hoist-non-react-statics": "3.3.1",
"@types/lodash-es": "4.17.3",
"@types/memoize-one": "5.1.2",
"@types/moment": "2.13.0",
"@types/mousetrap": "1.6.3",
"@types/node": "12.12.21",
"@types/path-parse": "1.0.19",
Expand Down
14 changes: 4 additions & 10 deletions shared/people/follow-notification/index.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as React from 'react'
import * as C from '../../constants/people'
import * as Sb from '../../stories/storybook'
import FollowNotification from '.'
import moment from 'moment'
import * as dateFns from 'date-fns'

const singleFollowProps1 = {
badged: true,
Expand All @@ -25,9 +25,7 @@ const singleContactProps = {
const singleFollowProps2 = {
badged: false,
newFollows: [C.makeFollowedNotification({username: 'max'})],
notificationTime: moment()
.subtract(3, 'days')
.toDate(),
notificationTime: dateFns.sub(new Date(), {days: 3}),
onClickUser: Sb.action('onClickUser'),
type: 'follow' as const,
}
Expand All @@ -39,9 +37,7 @@ const multiFollowProps1 = {
C.makeFollowedNotification({username: 'mmaxim'}),
C.makeFollowedNotification({username: 'chrisnojima'}),
],
notificationTime: moment()
.subtract(3, 'weeks')
.toDate(),
notificationTime: dateFns.sub(new Date(), {days: 21}), // 3 weeks
numAdditional: 0,
onClickUser: Sb.action('onClickUser'),
type: 'follow' as const,
Expand All @@ -63,9 +59,7 @@ const multiFollowProps2 = {
C.makeFollowedNotification({username: 'mlsteele'}),
C.makeFollowedNotification({username: 'joshblum'}),
],
notificationTime: moment()
.subtract(3, 'months')
.toDate(),
notificationTime: dateFns.sub(new Date(), {months: 3}),
numAdditional: 5,
onClickUser: Sb.action('onClickUser'),
type: 'follow' as const,
Expand Down
6 changes: 4 additions & 2 deletions shared/settings/invites/index.desktop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import * as Styles from '../../styles'
import * as Types from '../../constants/types/settings'
import React, {Component} from 'react'
import SubHeading from '../subheading'
import moment from 'moment'
import {Props} from '.'
import {intersperseFn} from '../../util/arrays'
import * as dateFns from 'date-fns'

type State = {
inviteEmail: string
Expand Down Expand Up @@ -163,7 +163,9 @@ function PendingEmailContent({
<Kb.Text type="BodySemibold" onClick={() => onSelectPendingInvite(invite)}>
{invite.email}
</Kb.Text>
<Kb.Text type="BodySmall">Invited {moment.unix(invite.created).format('MMM D, YYYY')}</Kb.Text>
<Kb.Text type="BodySmall">
Invited {dateFns.format(dateFns.fromUnixTime(invite.created), 'MMM d, yyyy')}
</Kb.Text>
</Kb.Box>
</Kb.Box>
)
Expand Down
Loading

0 comments on commit 80d105a

Please sign in to comment.