Skip to content

Commit

Permalink
adjust for backend changes
Browse files Browse the repository at this point in the history
  • Loading branch information
tom-james-watson committed Apr 25, 2021
1 parent 9200f23 commit c105047
Show file tree
Hide file tree
Showing 7 changed files with 1,332 additions and 11,394 deletions.
127 changes: 46 additions & 81 deletions components/game.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, { useState } from "react";
import * as tweenFunctions from "tween-functions";
import moment from "moment";
import {
DragDropContext,
DropResult,
Expand All @@ -12,14 +11,6 @@ import NextItemList from "./next-item-list";
import PlayedItemList from "./played-item-list";
import styles from "../styles/game.module.scss";

function noop() {
// noop
}

function timeout(ms: number) {
return new Promise((res) => setTimeout(res, ms));
}

interface State {
badlyPlaced: {
index: number;
Expand Down Expand Up @@ -67,9 +58,7 @@ function moveStepByStep(
if (newPosition === undefined || newScroll === undefined) {
drag.drop();
} else {
// console.log({ newPosition });
bottom.scrollLeft = newScroll;
// console.log(bottom.scrollLeft);
drag.move({ x: newPosition, y: 0 });
moveStepByStep(drag, transformValues, scrollValues);
}
Expand All @@ -85,17 +74,12 @@ async function useAutoMoveSensor(state: State, api: SensorAPI) {
return;
}

const preDrag = api.tryGetLock?.(
state.played[state.badlyPlaced.index].id,
noop
);
const preDrag = api.tryGetLock?.(state.played[state.badlyPlaced.index].id);

if (!preDrag) {
return;
}

// await timeout(500);

const itemEl: HTMLElement | null = document.querySelector(
`[data-rbd-draggable-id='${state.played[state.badlyPlaced.index].id}']`
);
Expand All @@ -110,90 +94,56 @@ async function useAutoMoveSensor(state: State, api: SensorAPI) {
throw new Error("Can't find element");
}

// const bottomElLeft = bottomEl.scrollLeft;
// const bottomElRight = bottomEl.scrollLeft + bottomEl.clientWidth;
// const bottomElThirdWidth = bottomEl.clientWidth / 3;
const bottomElCentreLeft = bottomEl.scrollLeft + bottomEl.clientWidth / 4;
const bottomElCentreRight =
bottomEl.scrollLeft + (bottomEl.clientWidth / 4) * 3 - itemEl.clientWidth;

let distance = 0;
let scrollDistance = 0;

if (
destEl.offsetLeft < bottomElCentreLeft ||
destEl.offsetLeft > bottomElCentreRight
) {
// Destination is not in centre third of the screen.
// Calculate distance to cover

distance =
// Destination is not in middle two quarters of the screen. Calculate
// distance we therefore need to scroll.
scrollDistance =
destEl.offsetLeft < bottomElCentreLeft
? destEl.offsetLeft - bottomElCentreLeft
: destEl.offsetLeft - bottomElCentreRight;

console.log({
distance,
width: bottomEl.clientWidth,
current: bottomEl.scrollLeft,
future: bottomEl.scrollLeft + distance,
});

if (bottomEl.scrollLeft + distance < 0) {
distance = -bottomEl.scrollLeft;
if (bottomEl.scrollLeft + scrollDistance < 0) {
scrollDistance = -bottomEl.scrollLeft;
} else if (
bottomEl.scrollLeft + distance >
bottomEl.scrollLeft + scrollDistance >
bottomEl.scrollWidth - bottomEl.clientWidth
) {
distance =
scrollDistance =
bottomEl.scrollWidth - bottomEl.clientWidth - bottomEl.scrollLeft;
}

console.log({
distance,
width: bottomEl.clientWidth,
current: bottomEl.scrollLeft,
future: bottomEl.scrollLeft + distance,
});
}

// const destOnScreen = destEl.offsetWidth;
// bottomEl.scrollLeft;
// bottomEl.clientWidth;

// console.log(itemEl.offsetLeft);

// console.log({ destEl });
// console.log(destEl.offsetLeft);

// destEl.scrollIntoView({ inline: "center", behavior: "smooth" });

// await wait(1000);

// console.log(itemEl.offsetLeft);
// console.log(destEl.offsetLeft);

const moveDistance = destEl.offsetLeft - itemEl.offsetLeft - distance;
// Calculate the distance we need to move the item after taking into account
// how far we are scrolling.
const transformDistance =
destEl.offsetLeft - itemEl.offsetLeft - scrollDistance;

const drag = preDrag.fluidLift({ x: 0, y: 0 });

// Create a series of eased transformations and scrolls to animate from the
// current state to the desired state.
const transformPoints = [];
const scrollPoints = [];

const numberOfPoints = 10 * Math.abs(state.badlyPlaced.delta);

console.log({
moveDistance,
});
const numberOfPoints = 30 + 5 * Math.abs(state.badlyPlaced.delta);

for (let i = 0; i < numberOfPoints; i++) {
transformPoints.push(
tweenFunctions.easeOutCirc(i, 0, moveDistance, numberOfPoints)
tweenFunctions.easeOutCirc(i, 0, transformDistance, numberOfPoints)
);
scrollPoints.push(
tweenFunctions.easeOutCirc(
i,
bottomEl.scrollLeft,
bottomEl.scrollLeft + distance,
bottomEl.scrollLeft + scrollDistance,
numberOfPoints
)
);
Expand All @@ -211,26 +161,44 @@ export default function Game() {
played: [],
});
function getRandomItem(deck: Item[], played: Item[]): Item {
let next: Item;

const playedYears = played.map((item): number => {
return item.year;
});

console.log({ playedYears });
let item: Item | undefined = undefined;
let iterations = 0;

const periods: [number, number][] = [
[-100000, 1000],
[1000, 1800],
[1800, 1920],
[1920, 1960],
[1960, 2020],
];
const [fromYear, toYear] = periods[
Math.floor(Math.random() * periods.length)
];

while (item === undefined) {
iterations += 1;

if (iterations > 1000) {
throw new Error(`Couldn't find item after ${iterations} iterations`);
}

const index = Math.floor(Math.random() * deck.length);
next = deck[index];
const year = moment(next.date).year();
const candidate = deck[index];

if (playedYears.includes(year)) {
if (candidate.year < fromYear || candidate.year > toYear) {
continue;
}

deck.splice(index, 1);
if (playedYears.includes(candidate.year)) {
continue;
}

item = { ...next, year };
deck.splice(index, 1);
item = { ...candidate };
}

return item;
Expand All @@ -250,11 +218,6 @@ export default function Game() {
const played = [
{ ...getRandomItem(deck, []), played: { correct: true } },
];
// const played: PlayedItem[] = [];
// for (let x = 0; x < 10; x++) {
// played.push({ ...getRandomItem(deck, []), played: { correct: true } });
// }
// played.sort((a, b) => a.year - b.year);

setState((state) => {
return { ...state, next, deck, played, loaded: true };
Expand Down Expand Up @@ -334,6 +297,8 @@ export default function Game() {
}
}, [state]);

console.log(state);

return (
<>
{state.loaded ? (
Expand Down
65 changes: 28 additions & 37 deletions components/item-card.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from "react";
import moment from "moment";
import classNames from "classnames";
import { useSpring, animated } from "react-spring";
import { Draggable } from "react-beautiful-dnd";
Expand Down Expand Up @@ -27,32 +26,14 @@ const datePropIdMap: { [datePropId: string]: string } = {
P8556: "extinction",
P6949: "announcement",
P1319: "earliest",
P569: "birth",
P570: "death",
P582: "end",
P580: "start",
P7125: "latest one",
P7124: "first one",
};

// const datePropIdMap2: { [datePropId: string]: string } = {
// P575: "Discovery or invention of",
// P7589: "Assent of ",
// P577: "Publication of",
// P1191: "First performance of",
// P1619: "Official opening of",
// P571: "Creation of",
// P1249: "Earliest written record of",
// P576: "Abolishing or demolishing of",
// P8556: "Extinction of",
// P6949: "Announcement of",
// P1319: "Earliest record of",
// P570: "Death of",
// P582: "End of",
// P580: "Start of",
// P7125: "Date of latest",
// P7124: "Date of first",
// };

function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
Expand All @@ -70,17 +51,19 @@ export default function ItemCard(props: Props) {

const fadeProps = useSpring({ opacity: 1, from: { opacity: 0 } });

const imgUrl = item.image
? `url(https://commons.wikimedia.org/w/index.php?title=Special:Redirect/file/${encodeURIComponent(
item.image
)}&width=300)`
: undefined;
const type = React.useMemo(() => {
const safeDescription = item.description.replace(/ \(.+\)/g, "");

item.date_prop_id;
if (item.description.length < 60 && !/\d\d/.test(safeDescription)) {
return item.description.replace(/ \(.+\)/g, "");
}

const year = moment(item.date).year();
if (item.instance_of.includes("human") && item.occupations !== null) {
return item.occupations[0];
}

const yearStr = year < -10000 ? year.toLocaleString() : year.toString();
return item.instance_of[0];
}, [item]);

return (
<Draggable draggableId={item.id} index={index} isDragDisabled={!draggable}>
Expand Down Expand Up @@ -108,14 +91,17 @@ export default function ItemCard(props: Props) {
style={{ opacity: opacity.to((o) => 1 - o), transform }}
>
<div className={styles.top}>
<span className={styles.label}>{capitalize(item.label)}</span>
{item.types.length > 0 && (
<div className={styles.types}>
<span className={styles.type}>{item.types[0]}</span>
</div>
)}
<div className={styles.label}>{capitalize(item.label)}</div>
<div className={styles.description}>{capitalize(type)}</div>
</div>
<div className={styles.bottom} style={{ backgroundImage: imgUrl }}>
<div
className={styles.bottom}
style={{
backgroundImage: `url('https://commons.wikimedia.org/w/index.php?title=Special:Redirect/file/${encodeURIComponent(
item.image
)}&width=300')`,
}}
>
{played ? (
<animated.div style={fadeProps} className={styles.playedInfo}>
<span
Expand All @@ -125,7 +111,9 @@ export default function ItemCard(props: Props) {
"played" in item && !item.played.correct,
})}
>
{yearStr}
{item.year < -10000
? item.year.toLocaleString()
: item.year.toString()}
</span>
</animated.div>
) : (
Expand All @@ -145,10 +133,13 @@ export default function ItemCard(props: Props) {
}}
>
<span className={styles.label}>{capitalize(item.label)}</span>
<span className={styles.date}>
{capitalize(datePropIdMap[item.date_prop_id])}: {item.year}
</span>
<span className={styles.description}>{item.description}.</span>
<a
href={`https://www.wikipedia.org/wiki/${encodeURIComponent(
item.wikipedia
item.wikipedia_title
)}`}
className={styles.wikipedia}
target="_blank"
Expand Down
5 changes: 0 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
},
"dependencies": {
"classnames": "^2.3.1",
"moment": "^2.29.1",
"next": "10.1.3",
"react": "17.0.2",
"react-beautiful-dnd": "^13.1.0",
Expand Down
Loading

0 comments on commit c105047

Please sign in to comment.