Skip to content

Commit

Permalink
Merge pull request #661 from isucon/post-message-client-ride
Browse files Browse the repository at this point in the history
[FE] ISURIDEボタン押下時にpost-messageを飛ばす
  • Loading branch information
imamiya-masaki authored Dec 6, 2024
2 parents 62739c0 + 5ca8c44 commit 856ae18
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 28 deletions.
1 change: 0 additions & 1 deletion frontend/app/contexts/owner-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ export const OwnerProvider = ({ children }: { children: ReactNode }) => {
void (async () => {
try {
const sales = await fetchOwnerGetSales({
// TODO: 機能していない?
queryParams: {
since: timestamp(since),
until: timestamp(until),
Expand Down
25 changes: 24 additions & 1 deletion frontend/app/contexts/simulator-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ import {
fetchChairGetNotification,
} from "~/api/api-components";
import { SimulatorChair } from "~/types";
import { getSimulatorCurrentCoordinate } from "~/utils/storage";
import { getCookieValue } from "~/utils/get-cookie-value";
import { Message, MessageTypes } from "~/utils/post-message";
import { getSimulatorCurrentCoordinate } from "~/utils/storage";

type SimulatorContextProps = {
chair?: SimulatorChair;
data?: ChairGetNotificationResponse["data"];
setCoordinate?: (coordinate: Coordinate) => void;
setToken?: (token: string) => void;
isAnotherSimulatorBeingUsed?: boolean;
};

const SimulatorContext = createContext<SimulatorContextProps>({});
Expand Down Expand Up @@ -186,13 +188,34 @@ export const SimulatorProvider = ({ children }: { children: ReactNode }) => {
return coordinate ?? { latitude: 0, longitude: 0 };
});

const [clientRideId, setClientRideId] = useState<string>();
const isAnotherSimulatorBeingUsed = !clientRideId && !!data?.ride_id;

console.log(isAnotherSimulatorBeingUsed);

useEffect(() => {
const onMessage = ({
data,
}: MessageEvent<Message["ClientRideRequested"]>) => {
const isSameOrigin = origin == location.origin;
if (isSameOrigin && data.type === MessageTypes.ClientRideRequested) {
setClientRideId(data?.payload?.rideId);
}
};
window.addEventListener("message", onMessage);
return () => {
window.removeEventListener("message", onMessage);
};
}, []);

return (
<SimulatorContext.Provider
value={{
data,
chair: simulateChair ? { ...simulateChair, coordinate } : undefined,
setCoordinate,
setToken,
isAnotherSimulatorBeingUsed,
}}
>
{children}
Expand Down
42 changes: 18 additions & 24 deletions frontend/app/routes/client._index/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import { Button } from "~/components/primitives/button/button";
import { Modal } from "~/components/primitives/modal/modal";
import { Text } from "~/components/primitives/text/text";
import { useClientContext } from "~/contexts/client-context";
import { NearByChair, isClientApiError } from "~/types";
import { sendClientReady } from "~/utils/post-message";
import { NearByChair } from "~/types";
import { sendClientReady, sendClientRideRequested } from "~/utils/post-message";
import { Arrived } from "./driving-state/arrived";
import { Carrying } from "./driving-state/carrying";
import { Enroute } from "./driving-state/enroute";
Expand All @@ -36,6 +36,7 @@ type EstimatePrice = { fare: number; discount: number };

export default function Index() {
const { data } = useClientContext();
const emulateChairs = useGhostChairs();
const [internalRideStatus, setInternalRideStatus] = useState<RideStatus>();
const [currentLocation, setCurrentLocation] = useState<Coordinate>();
const [destLocation, setDestLocation] = useState<Coordinate>();
Expand All @@ -44,28 +45,27 @@ export default function Index() {
const [displayedChairs, setDisplayedChairs] = useState<NearByChair[]>([]);
const [centerCoordinate, setCenterCoodirnate] = useState<Coordinate>();
const onCenterMove = useCallback(
(coordinate: Coordinate) => {
setCenterCoodirnate(coordinate);
},
[setCenterCoodirnate],
(coordinate: Coordinate) => setCenterCoodirnate(coordinate),
[],
);
const onSelectMove = useCallback(
(coordinate: Coordinate) => setSelectedLocation(coordinate),
[],
);
const onSelectMove = useCallback((coordinate: Coordinate) => {
setSelectedLocation(coordinate);
}, []);
const [isLocationSelectorModalOpen, setLocationSelectorModalOpen] =
useState(false);
const locationSelectorModalRef = useRef<HTMLElement & { close: () => void }>(
null,
);
const statusModalRef = useRef<HTMLElement & { close: () => void }>(null);
const [estimatePrice, setEstimatePrice] = useState<EstimatePrice>();
const handleConfirmLocation = useCallback(() => {
if (direction === "from") {
setCurrentLocation(selectedLocation);
} else if (direction === "to") {
setDestLocation(selectedLocation);
}
if (locationSelectorModalRef.current) {
locationSelectorModalRef.current.close();
}
locationSelectorModalRef.current?.close();
}, [direction, selectedLocation]);

const isStatusModalOpen = useMemo(() => {
Expand All @@ -77,10 +77,6 @@ export default function Index() {
);
}, [internalRideStatus]);

const statusModalRef = useRef<HTMLElement & { close: () => void }>(null);
const [estimatePrice, setEstimatePrice] = useState<EstimatePrice>();
const emulateChairs = useGhostChairs();

useEffect(() => {
setInternalRideStatus(data?.status);
}, [data?.status]);
Expand Down Expand Up @@ -110,16 +106,15 @@ export default function Index() {
}
setInternalRideStatus("MATCHING");
try {
void (await fetchAppPostRides({
const { ride_id } = await fetchAppPostRides({
body: {
pickup_coordinate: currentLocation,
destination_coordinate: destLocation,
},
}));
});
sendClientRideRequested(window.parent, { rideId: ride_id });
} catch (error) {
if (isClientApiError(error)) {
console.error(error);
}
console.error(error);
}
}, [currentLocation, destLocation]);

Expand All @@ -129,8 +124,7 @@ export default function Index() {
let abortController: AbortController | undefined;
let timeoutId: NodeJS.Timeout | undefined;

const updateNearByChairs = async (coordinate: Coordinate) => {
const { latitude, longitude } = coordinate;
const updateNearByChairs = async ({ latitude, longitude }: Coordinate) => {
try {
abortController?.abort();
abortController = new AbortController();
Expand Down Expand Up @@ -227,7 +221,7 @@ export default function Index() {
ref={locationSelectorModalRef}
onClose={() => setLocationSelectorModalOpen(false)}
>
<div className="flex flex-col items-center mt-4 h-full">
<div className="flex flex-col items-center h-full">
<div className="flex-grow w-full max-h-[75%] mb-6">
<Map
onMove={onSelectMove}
Expand Down
16 changes: 14 additions & 2 deletions frontend/app/utils/post-message.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
export const MessageTypes = {
ClientReady: "isuride.client.ready",
SimulatorConfing: "isuride.simulator.config",
ClientReady: "isuride.client.ready", // クライアントの画面準備完了
ClientRideRequested: "isuride.client.running", // クライアントでISURIDEが実行中
SimulatorConfing: "isuride.simulator.config", // シミュレーターからの設定値変更
} as const;

export type Message = {
ClientReady: {
type: typeof MessageTypes.ClientReady;
payload: { ready?: boolean };
};
ClientRideRequested: {
type: typeof MessageTypes.ClientRideRequested;
payload: { rideId?: string };
};
SimulatorConfing: {
type: typeof MessageTypes.SimulatorConfing;
payload: {
Expand All @@ -23,6 +28,13 @@ export const sendClientReady = (
target.postMessage({ type: MessageTypes.ClientReady, payload }, "*");
};

export const sendClientRideRequested = (
target: Window,
payload: NonNullable<Message["ClientRideRequested"]["payload"]>,
) => {
target.postMessage({ type: MessageTypes.ClientRideRequested, payload }, "*");
};

export const sendSimulatorConfig = (
target: Window,
payload: NonNullable<Message["SimulatorConfing"]["payload"]>,
Expand Down

0 comments on commit 856ae18

Please sign in to comment.