Skip to content

Commit

Permalink
Performance improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Metalloriff committed Sep 2, 2023
1 parent 706a00e commit 8fd5575
Show file tree
Hide file tree
Showing 15 changed files with 213 additions and 79 deletions.
2 changes: 1 addition & 1 deletion docs/assets/scripts/main.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions docs/assets/styles/main.css

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@
"open": "lt --port 3000 --local-host localhost",
"build": "npx webpack --mode production --env=mode=production"
}
}
}
26 changes: 18 additions & 8 deletions src/Classes/API.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Toasts from "../Components/Toasts";
import _ from "lodash";
import Toasts from "../Components/Toasts";
import UserStore from "./Stores/UserStore";

export default new class E621API {
Expand All @@ -22,14 +23,8 @@ export default new class E621API {
* @returns {string} An endpoint URL.
*/
getEndpoint(sub, args = {}, json = true) {
// Get the stored login data.
let login = this.loginData;
// If the login or api key is null, then clean the login object.
if (!login.login || !login.api_key) login = {};

// Create the request params object.
const params = new URLSearchParams({
...login,
...args,
_client: "Sucralose/2.0 by Metalloriff"
});
Expand All @@ -55,6 +50,10 @@ export default new class E621API {
// Set the last made request to the current time.
this.lastMadeRequest = Date.now();

// Apply authorization, if valid
const { login, api_key } = this.loginData;
login && api_key && _.set(restOptions, ["headers", "authorization"], "Basic " + btoa(`${login}:${api_key}`));

// Return the response object.
return await fetch(this.getEndpoint(sub, args, json), restOptions)
.then(response => json ? response.json() : response);
Expand Down Expand Up @@ -143,6 +142,17 @@ export default new class E621API {
{},
false,
{ method: "DELETE" }
).then(r => (delete this.#favoriting[postId], r));
).then(r => (delete this.#favoriting[postId], r)).catch(err => {
console.error(err);

// For when they inevitably still haven't fixed this issue.
Toasts.showToast(
<>
Due to an API issue on e621's side, it is currently impossible to unfavorite posts via their API. Please <a href={`https://e621.net/posts/${postId}#remove-fav-button`}>click here</a> to manually unfavorite it.
</>,
"Failure",
10
);
});
}
}
8 changes: 3 additions & 5 deletions src/Classes/Constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ export function joinClassNames() {
break;

default:
final += arguments[i];
if (arguments[i])
final += arguments[i];
break;
}

Expand Down Expand Up @@ -44,7 +45,7 @@ export function openFileDialog(options = {}) {
}

export function download(uri) {
return fetch(`https://api.allorigins.win/raw?url=${encodeURIComponent(uri)}`)
return fetch("https://cors-proxy.htmldriven.com/?url=" + encodeURIComponent(uri))
.then(res => res.blob())
.then(blob => {
const a = Object.assign(document.createElement("a"), {
Expand All @@ -53,11 +54,8 @@ export function download(uri) {
download: uri.split("/")[uri.split("/").length - 1]
});

document.body.appendChild(a);
a.click();

window.URL.revokeObjectURL(a.href);
a.remove();
})
.catch(err => (console.error(err), Toasts.showToast("Failed to save image!", "Failure")));
}
Expand Down
19 changes: 12 additions & 7 deletions src/Classes/Stores/UserStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import Store from "../Store";

const cache = {};
let localUser = null;
let _localSets;

const vapidKey = "BBWvMxlJ7kaRqFNxqnzChq6HE_wXmrt39gSgbsivwiccua2xFmK1qQqtPLtBQRkjBN0xM1HDlQ8ycbXaUiWulzo";

Expand Down Expand Up @@ -45,13 +46,17 @@ const UserStoreClass = class UserStore extends Store {
{
e621User,
signedIn: true,
sets: data.username && await API.request(
"post_sets",
{
commit: "Search",
"search[creator_name]": data.username
}
),
async getSets() {
if (!data.username) return null;

return _localSets ?? (_localSets = await API.request(
"post_sets",
{
commit: "Search",
"search[creator_name]": data.username
}
));
},

get firebaseSerialized() {
const output = {};
Expand Down
9 changes: 7 additions & 2 deletions src/Components/Modals.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,13 @@ function ImageComponent({ image, setLoaded, setFailed, className, onClick, isPre
const [loaded, _setLoaded] = React.useState(false);

const events = {
onLoad: () => (setLoaded?.(true), setFailed?.(false), _setLoaded(true)),
onLoad: e => {
e.target.decode().then(() => {
setLoaded?.(true);
setFailed?.(false);
_setLoaded(true);
});
},
onError: () => (setLoaded?.(true), setFailed?.(true), _setLoaded(true)),
onClick
};
Expand Down Expand Up @@ -421,7 +427,6 @@ export class Modals extends React.Component {

componentDidUpdate(prevProps, prevState, snapshot) {
document.documentElement.style.overflowY = this.state.stack.length ? "hidden" : null;
document.documentElement.style.marginRight = this.state.stack.length ? "5px" : null;
}

handleBackdropClick(e) {
Expand Down
14 changes: 12 additions & 2 deletions src/Components/Modals.scss
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
bottom: 0;
right: 0;

max-width: 100vw;

z-index: 10000;

> .ModalContainer {
Expand Down Expand Up @@ -108,8 +110,16 @@

max-height: 80vh;

.jsgif {
display: inline-flex;
justify-content: center;
align-items: center;
flex-direction: column;
}

img,
video {
video,
.jsgif, canvas {
max-width: 90vw;
height: 100%;

Expand Down Expand Up @@ -153,7 +163,7 @@
}

.LoadingIndicator {
background: $overlay;
background: rgba(black, 0.1);

position: absolute;
top: 0;
Expand Down
4 changes: 3 additions & 1 deletion src/Components/Modals/CreateSetModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ export default function CreateSetModal({ postId }) {
);

response.post_ids.push(postId);
UserStore.getLocalUser().sets.push(response);

const sets = await UserStore.getLocalUser().getSets();
sets.push(response);

Toasts.showToast("Successfully created set", "Success");
await Modals.pop();
Expand Down
22 changes: 15 additions & 7 deletions src/Components/Posts/Post.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import _ from "lodash";
import React from "react";
import React, { useEffect, useState } from "react";
import * as Feather from "react-feather";
import API from "../../Classes/API";
import { download, joinClassNames } from "../../Classes/Constants";
Expand Down Expand Up @@ -229,10 +229,10 @@ export default function Post({ post }) {
</ContextMenu.Wrapper>
)}

<Button tooltipText="Download" tooltipSide="right"
{/* <Button tooltipText="Download" tooltipSide="right"
onClick={events.download}>
<Feather.Download />
</Button>
</Button> */}

<LinkWrapper href={`post/${id}`}>
<Button tooltipText="View Post" tooltipSide="right">
Expand All @@ -248,13 +248,21 @@ export default function Post({ post }) {
}

export function PostContextMenu({ post }) {
const sets = UserStore.getLocalUser()?.sets ?? [];
const [sets, initSets] = useState([]);

useEffect(() => {
const user = UserStore.getLocalUser();

if (user) {
user.getSets().then(sets => initSets(sets));
}
})

const [, forceUpdate] = React.useReducer(x => x + 1, 0);

const events = {
toggleSet: async index => {
const set = UserStore.getLocalUser()?.sets[index];
const set = UserStore.getLocalUser()?.getSets?.()[index];
const postIndex = set.post_ids.indexOf(post.id);

if (postIndex !== -1) {
Expand Down Expand Up @@ -405,12 +413,12 @@ export function PostModalButtons({ post }) {
<Tooltip style={{ color: "var(--txt-color)" }}>Favorite</Tooltip>
</div>

<div className="Button Flex" style={{
{/* <div className="Button Flex" style={{
alignItems: "center", justifyContent: "center"
}} onClick={events.download}>
<Feather.Download />
<Tooltip style={{ color: "var(--txt-color)" }}>Download</Tooltip>
</div>
</div> */}

<div className="ModalArtistsList FlexCenter">
<div className="ArtistTag MainTag">Artists - </div>
Expand Down
12 changes: 6 additions & 6 deletions src/Components/Posts/TagItem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ export function TagItemContextMenu({ tag }) {
SearchField.handleSearch(SearchField.value.trim() + " " + tag),
subscribe: () => {
const localUser = UserStore.getLocalUser();
if (!Array.isArray(localUser.subscriptions)) localUser.subscriptions = [];
localUser.subscriptions = localUser.subscriptions ?? [];
localUser.subscriptions.push(tag);

Database.update(
Database.doc("users", localUser.uid),
localUser.firebaseSerialized
{ subscriptions: localUser.subscriptions }
).then(() => Toasts.showToast(<span>Added <b>{tag}</b> to subscribed tags</span>))
.catch(err => (console.error(err), Toasts.showToast("An unknown error occurred", "Failure")));
},
Expand All @@ -43,8 +43,8 @@ export function TagItemContextMenu({ tag }) {

Database.update(
Database.doc("users", localUser.uid),
localUser.firebaseSerialized
).then(() => Toasts.showToast(<span>Added <b>{tag}</b> to subscribed tags</span>))
{ subscriptions: localUser.subscriptions }
).then(() => Toasts.showToast(<span>Removed <b>{tag}</b> from subscribed tags</span>))
.catch(err => (console.error(err), Toasts.showToast("An unknown error occurred", "Failure")));
},
blacklist: () => {
Expand Down Expand Up @@ -81,11 +81,11 @@ export function TagItemContextMenu({ tag }) {
>Subscribe</ContextMenu.Item>
)}

<ContextMenu.Item
{/* <ContextMenu.Item
autoClose
icon={<Feather.EyeOff />}
onClick={events.blacklist}
>Blacklist</ContextMenu.Item>
>Blacklist</ContextMenu.Item> */}

<ContextMenu.Divider />
</React.Fragment>
Expand Down
7 changes: 1 addition & 6 deletions src/Components/TabsList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,7 @@ export default class extends React.Component {
))}
</div>

{children.map((child, i) => (
<div className="TabItem" key={i}
style={{ display: this.state.active === i ? "block" : "none" }}>
{child}
</div>
))}
{children[this.state.active]}
</div>
);
}
Expand Down
12 changes: 12 additions & 0 deletions src/Pages/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,12 @@ export const newsPosts = [{
Post modal -- There's now artist tags underneath the controls on the post modal. Open a post and see an art style you really like? Now you can be lazy and don't have to close the modal to view their other works.
</p>

<p>Sets -- The sets page is now a little less buggy, and favorite sets has been added! You can right click or tap and hold on a set to toggle favorite, and there's a favorites tab in the sets page.</p>

<p>
The download button has been temporarily/permanently removed. For now, right click/tap and hold and hit save as. It will be re-added if I can find an efficient way to do it.
</p>

<h2>Patched bugs</h2>

<p>
Expand All @@ -258,8 +264,14 @@ export const newsPosts = [{
Fixed the popular page.
</p>

<p>Fixed a Firefox-specific bug causing image flashing on the modals.</p>

<p>Fixed an intentional(? I do not know what me 2 years ago was thinking) bug causing the entire page to shift 5 pixels when opening an image.</p>

<p>(Potentially) fixed a bug causing scrolling to randomly say you've reached the end, when you have not. This requires longer testing, as it wasn't easily reproducable.</p>

<p>Fixed adding and removing to and from subscriptions via context menu.</p>

<h2>What's next?</h2>

<p>
Expand Down
Loading

0 comments on commit 8fd5575

Please sign in to comment.