Skip to content

Commit

Permalink
Replace momentjs with date-fns
Browse files Browse the repository at this point in the history
  • Loading branch information
SleeplessOne1917 committed Jun 22, 2023
1 parent f5b958f commit d0dff77
Show file tree
Hide file tree
Showing 12 changed files with 187 additions and 79 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,5 @@ package-lock.json

src/shared/translations

stats.json

1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
src/shared/translations
lemmy-translations
src/assets/css/themes/*.css
stats.json
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
"license": "AGPL-3.0",
"author": "Dessalines <tyhou13@gmx.com>",
"scripts": {
"analyze": "webpack --mode=none",
"prebuild:dev": "yarn clean && node generate_translations.js",
"build:dev": "webpack --mode=development",
"prebuild:prod": "yarn clean && node generate_translations.js",
"build:prod": "webpack --mode=production",
"clean": "yarn run rimraf dist",
"dev": "yarn start",
"dev": "yarn build:dev --watch",
"lint": "yarn translations:generate && tsc --noEmit && eslint --report-unused-disable-directives --ext .js,.ts,.tsx \"src/**\" && prettier --check \"src/**/*.{ts,tsx,js,css,scss}\"",
"prepare": "husky install",
"start": "yarn build:dev --watch",
"themes:build": "sass src/assets/css/themes/:src/assets/css/themes",
"themes:watch": "sass --watch src/assets/css/themes/:src/assets/css/themes",
"translations:generate": "node generate_translations.js",
Expand Down Expand Up @@ -51,6 +51,7 @@
"copy-webpack-plugin": "^11.0.0",
"cross-fetch": "^3.1.5",
"css-loader": "^6.7.3",
"date-fns": "^2.30.0",
"emoji-mart": "^5.4.0",
"emoji-short-name": "^2.0.0",
"express": "~4.18.2",
Expand All @@ -76,7 +77,7 @@
"markdown-it-sub": "^1.0.0",
"markdown-it-sup": "^1.0.0",
"mini-css-extract-plugin": "^2.7.5",
"moment": "^2.29.4",
"path-browserify": "^1.0.1",
"register-service-worker": "^1.7.2",
"run-node-webpack-plugin": "^1.3.0",
"sanitize-html": "^2.10.0",
Expand All @@ -101,6 +102,7 @@
"@types/markdown-it": "^12.2.3",
"@types/markdown-it-container": "^2.0.5",
"@types/node": "^20.1.2",
"@types/path-browserify": "^1.0.0",
"@types/sanitize-html": "^2.9.0",
"@types/serialize-javascript": "^5.0.1",
"@types/toastify-js": "^1.11.1",
Expand All @@ -122,6 +124,7 @@
"style-loader": "^3.3.2",
"terser": "^5.17.3",
"typescript": "^5.0.4",
"webpack-bundle-analyzer": "^4.9.0",
"webpack-dev-server": "4.15.0"
},
"packageManager": "yarn@1.22.19",
Expand Down
37 changes: 27 additions & 10 deletions src/client/index.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,39 @@
import { initializeSite } from "@utils/app";
import setDefaultOptions from "date-fns/setDefaultOptions";
import { hydrate } from "inferno-hydrate";
import { Router } from "inferno-router";
import { App } from "../shared/components/app/app";
import { HistoryService } from "../shared/services";
import { HistoryService, I18NextService } from "../shared/services";

import "bootstrap/js/dist/collapse";
import "bootstrap/js/dist/dropdown";

initializeSite(window.isoData.site_res);
async function startClient() {
initializeSite(window.isoData.site_res);

const wrapper = (
<Router history={HistoryService.history}>
<App />
</Router>
);
const lang = I18NextService.i18n.language;
const locale = (
await import(
/* webpackExclude: /\.js\.flow$/ */
`date-fns/locale/${lang}`
)
).default;

const root = document.getElementById("root");
setDefaultOptions({
locale,
});

if (root) {
hydrate(wrapper, root);
const wrapper = (
<Router history={HistoryService.history}>
<App />
</Router>
);

const root = document.getElementById("root");

if (root) {
hydrate(wrapper, root);
}
}

startClient();
14 changes: 13 additions & 1 deletion src/server/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import setDefaultOptions from "date-fns/setDefaultOptions";
import express from "express";
import path from "path";
import process from "process";
import { I18NextService } from "../shared/services";
import CatchAllHandler from "./handlers/catch-all-handler";
import ManifestHandler from "./handlers/manifest-handler";
import RobotsHandler from "./handlers/robots-handler";
Expand Down Expand Up @@ -34,7 +36,17 @@ server.listen(Number(port), hostname, () => {
console.log(`http://${hostname}:${port}`);
});

process.on("SIGINT", () => {
process.on("SIGINT", async () => {
const lang = I18NextService.i18n.language;
const locale = (
await import(
/* webpackExclude: /\.js\.flow$/ */
`date-fns/locale/${lang}`
)
).default;
setDefaultOptions({
locale,
});
console.info("Interrupted");
process.exit(0);
});
10 changes: 6 additions & 4 deletions src/shared/components/comment/comment-node.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ import {
isMod,
} from "@utils/roles";
import classNames from "classnames";
import isBefore from "date-fns/isBefore";
import parseISO from "date-fns/parseISO";
import subMinutes from "date-fns/subMinutes";
import { Component, InfernoNode, linkEvent } from "inferno";
import { Link } from "inferno-router";
import {
Expand Down Expand Up @@ -46,7 +49,6 @@ import {
SaveComment,
TransferCommunity,
} from "lemmy-js-client";
import moment from "moment";
import { commentTreeMaxDepth } from "../../config";
import {
BanType,
Expand Down Expand Up @@ -1451,9 +1453,9 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
}

get isCommentNew(): boolean {
const now = moment.utc().subtract(10, "minutes");
const then = moment.utc(this.commentView.comment.published);
return now.isBefore(then);
const now = subMinutes(new Date(), 10);
const then = parseISO(this.commentView.comment.published);
return isBefore(now, then);
}

handleCommentCollapse(i: CommentNode) {
Expand Down
24 changes: 12 additions & 12 deletions src/shared/components/common/moment-time.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { capitalizeFirstLetter } from "@utils/helpers";
import format from "date-fns/format";
import formatDistanceToNow from "date-fns/formatDistanceToNow";
import parseISO from "date-fns/parseISO";
import { Component } from "inferno";
import moment from "moment";
import { I18NextService } from "../../services";
import { Icon } from "./icon";

Expand All @@ -11,22 +13,24 @@ interface MomentTimeProps {
ignoreUpdated?: boolean;
}

function momentFormat(input: string) {
return format(parseISO(input), "PPPPpppp");
}

export class MomentTime extends Component<MomentTimeProps, any> {
constructor(props: any, context: any) {
super(props, context);

moment.locale([...I18NextService.i18n.languages]);
}

createdAndModifiedTimes() {
const updated = this.props.updated;
let line = `${capitalizeFirstLetter(
I18NextService.i18n.t("created")
)}: ${this.format(this.props.published)}`;
)}: ${momentFormat(this.props.published)}`;
if (updated) {
line += `\n\n\n${capitalizeFirstLetter(
I18NextService.i18n.t("modified")
)} ${this.format(updated)}`;
)} ${momentFormat(updated)}`;
}
return line;
}
Expand All @@ -39,23 +43,19 @@ export class MomentTime extends Component<MomentTimeProps, any> {
className="moment-time font-italics pointer unselectable"
>
<Icon icon="edit-2" classes="icon-inline me-1" />
{moment.utc(this.props.updated).fromNow(!this.props.showAgo)}
{formatDistanceToNow(parseISO(this.props.updated))}
</span>
);
} else {
const published = this.props.published;
return (
<span
className="moment-time pointer unselectable"
data-tippy-content={this.format(published)}
data-tippy-content={momentFormat(published)}
>
{moment.utc(published).fromNow(!this.props.showAgo)}
{formatDistanceToNow(parseISO(published))}
</span>
);
}
}

format(input: string): string {
return moment.utc(input).local().format("LLLL");
}
}
13 changes: 9 additions & 4 deletions src/shared/components/modlog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import {
import { amAdmin, amMod } from "@utils/roles";
import type { QueryParams } from "@utils/types";
import { Choice, RouteDataResponse } from "@utils/types";
import formatDistanceToNowStrict from "date-fns/formatDistanceToNowStrict";
import parseISO from "date-fns/parseISO";
import { NoOptionI18nKeys } from "i18next";
import { Component, linkEvent } from "inferno";
import { T } from "inferno-i18next-dess";
Expand Down Expand Up @@ -44,7 +46,6 @@ import {
ModlogActionType,
Person,
} from "lemmy-js-client";
import moment from "moment";
import { fetchLimit } from "../config";
import { InitialFetchRequest } from "../interfaces";
import { FirstLoadService, I18NextService } from "../services";
Expand Down Expand Up @@ -118,6 +119,10 @@ function getActionFromString(action?: string): ModlogActionType {
return action !== undefined ? (action as ModlogActionType) : "All";
}

function getExpires(expires: string) {
return formatDistanceToNowStrict(parseISO(expires));
}

const getModlogActionMapper =
(
actionType: ModlogActionType,
Expand Down Expand Up @@ -371,7 +376,7 @@ function renderModlogType({ type_, view }: ModlogType) {
)}
{expires && (
<span>
<div>expires: {moment.utc(expires).fromNow()}</div>
<div>expires: {getExpires(expires)}</div>
</span>
)}
</>
Expand Down Expand Up @@ -403,7 +408,7 @@ function renderModlogType({ type_, view }: ModlogType) {
)}
{expires && (
<span>
<div>expires: {moment.utc(expires).fromNow()}</div>
<div>expires: {getExpires(expires)}</div>
</span>
)}
</>
Expand Down Expand Up @@ -467,7 +472,7 @@ function renderModlogType({ type_, view }: ModlogType) {
)}
{expires && (
<span>
<div>expires: {moment.utc(expires).fromNow()}</div>
<div>expires: {getExpires(expires)}</div>
</span>
)}
</>
Expand Down
8 changes: 3 additions & 5 deletions src/shared/components/person/profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { canMod, isAdmin, isBanned } from "@utils/roles";
import type { QueryParams } from "@utils/types";
import { RouteDataResponse } from "@utils/types";
import classNames from "classnames";
import format from "date-fns/format";
import parseISO from "date-fns/parseISO";
import { NoOptionI18nKeys } from "i18next";
import { Component, linkEvent } from "inferno";
import { Link } from "inferno-router";
Expand Down Expand Up @@ -70,7 +72,6 @@ import {
SortType,
TransferCommunity,
} from "lemmy-js-client";
import moment from "moment";
import { fetchLimit, relTags } from "../../config";
import { InitialFetchRequest, PersonDetailsView } from "../../interfaces";
import { mdToHtml } from "../../markdown";
Expand Down Expand Up @@ -613,10 +614,7 @@ export class Profile extends Component<
<Icon icon="cake" />
<span className="ms-2">
{I18NextService.i18n.t("cake_day_title")}{" "}
{moment
.utc(pv.person.published)
.local()
.format("MMM DD, YYYY")}
{format(parseISO(pv.person.published), "PPP")}
</span>
</div>
{!UserService.Instance.myUserInfo && (
Expand Down
34 changes: 7 additions & 27 deletions src/shared/utils/helpers/is-cake-day.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,13 @@
import moment from "moment";

moment.updateLocale("en", {
relativeTime: {
future: "in %s",
past: "%s ago",
s: "<1m",
ss: "%ds",
m: "1m",
mm: "%dm",
h: "1h",
hh: "%dh",
d: "1d",
dd: "%dd",
w: "1w",
ww: "%dw",
M: "1M",
MM: "%dM",
y: "1Y",
yy: "%dY",
},
});
import getDayOfYear from "date-fns/getDayOfYear";
import getYear from "date-fns/getYear";
import parseISO from "date-fns/parseISO";

export default function isCakeDay(published: string): boolean {
const createDate = moment.utc(published).local();
const currentDate = moment(new Date());
const createDate = parseISO(published);
const currentDate = new Date();

return (
createDate.date() === currentDate.date() &&
createDate.month() === currentDate.month() &&
createDate.year() !== currentDate.year()
getDayOfYear(createDate) === getDayOfYear(currentDate) &&
getYear(createDate) !== getYear(currentDate)
);
}
9 changes: 4 additions & 5 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const CopyPlugin = require("copy-webpack-plugin");
const RunNodeWebpackPlugin = require("run-node-webpack-plugin");
const merge = require("lodash/merge");
const { ServiceWorkerPlugin } = require("service-worker-webpack");
const BundleAnalyzerPlugin =
require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const banner = `
hash:[contentHash], chunkhash:[chunkhash], name:[name], filebase:[base], query:[query], file:[file]
Source code: https://github.com/LemmyNet/lemmy-ui
Expand Down Expand Up @@ -153,11 +155,8 @@ const createClientConfig = (_env, mode) => {
],
});

if (mode === "development") {
// config.cache = {
// type: "filesystem",
// name: "client",
// };
if (mode === "none") {
config.plugins.push(new BundleAnalyzerPlugin());
}

return config;
Expand Down

0 comments on commit d0dff77

Please sign in to comment.