LED表示機能第一段リファクタリング

This commit is contained in:
harukin-DeskMini 2023-01-28 03:27:41 +09:00
parent ff48198c87
commit 7321f6d514
2 changed files with 297 additions and 223 deletions

View File

@ -5,6 +5,7 @@ import { widthPercentageToDP as wp } from "react-native-responsive-screen";
import { customTrainDataDetector } from "../custom-train-data"; import { customTrainDataDetector } from "../custom-train-data";
import { useInterval } from "../../lib/useInterval"; import { useInterval } from "../../lib/useInterval";
import trainList from "../../assets/originData/trainList"; import trainList from "../../assets/originData/trainList";
import { objectIsEmpty } from "../../lib/objectIsEmpty";
let diagramData = undefined; let diagramData = undefined;
@ -43,14 +44,27 @@ export default function LED_vision(props) {
referer: "https://train.jr-shikoku.co.jp/sp.html", referer: "https://train.jr-shikoku.co.jp/sp.html",
}, },
}; };
const [trainDiagram, setTrainDiagram] = useState(null); const [trainDiagram, setTrainDiagram] = useState(null); // 全列車のダイヤを列番ベースで整理
const [stationDiagram, setStationDiagram] = useState(null); const [stationDiagram, setStationDiagram] = useState({}); //当該駅の全時刻表
const [currentTrain, setCurrentTrain] = useState(null); const [currentTrain, setCurrentTrain] = useState(null); //現在在線中の全列車
const [finalSwitch, setFinalSwitch] = useState(false); const [finalSwitch, setFinalSwitch] = useState(false);
const [trainIDSwitch, setTrainIDSwitch] = useState(false); const [trainIDSwitch, setTrainIDSwitch] = useState(false);
const [trainDescriptionSwitch, setTrainDescriptionSwitch] = useState(false); const [trainDescriptionSwitch, setTrainDescriptionSwitch] = useState(false);
const parseAllTrainDiagram = (text) => {
const val = text.replace("[\r\n", "").split(",\r\n");
let trainDiagram = {};
val.forEach((element) => {
try {
let data = JSON.parse(element);
Object.keys(data).forEach((key) => (trainDiagram[key] = data[key]));
} catch (e) {}
});
return trainDiagram;
};
useEffect(() => { useEffect(() => {
//全列車リストを生成する副作用
fetch( fetch(
"https://train.jr-shikoku.co.jp/g?arg1=station&arg2=traintimeinfo&arg3=dia", "https://train.jr-shikoku.co.jp/g?arg1=station&arg2=traintimeinfo&arg3=dia",
HeaderConfig HeaderConfig
@ -58,56 +72,57 @@ export default function LED_vision(props) {
.then((response) => response.text()) .then((response) => response.text())
.then((d) => { .then((d) => {
if (d.indexOf("<title>404 Not Found</title>") != -1) throw Error; if (d.indexOf("<title>404 Not Found</title>") != -1) throw Error;
const val = d.replace("[\r\n", "").split(",\r\n"); setTrainDiagram(parseAllTrainDiagram(d));
let trainDiagram = {};
val.forEach((element) => {
try {
let data = JSON.parse(element);
Object.keys(data).forEach((key) => (trainDiagram[key] = data[key]));
} catch (e) {}
});
setTrainDiagram(trainDiagram);
return trainDiagram;
})
.then((trainDiagram) => {
let returnData = {};
if (!trainDiagram) {
setStationDiagram(returnData);
return;
}
Object.keys(trainDiagram).forEach((key) => {
if (trainDiagram[key].match(props.station.Station_JP)) {
returnData[key] = trainDiagram[key];
}
});
setStationDiagram(returnData);
}) })
.catch((d) => { .catch((d) => {
console.log("fallback"); console.log("fallback");
setTrainDiagram(trainList); setTrainDiagram(trainList);
let returnData = {};
if (!trainList) {
setStationDiagram(returnData);
return;
}
Object.keys(trainList).forEach((key) => {
if (trainList[key].match(props.station.Station_JP)) {
returnData[key] = trainList[key];
}
});
setStationDiagram(returnData);
}); });
}, []); }, []);
const getTime = () => { useEffect(() => {
const returnData = []; //駅の情報を作成する副作用
Object.keys(stationDiagram).forEach((d) => { if (!trainDiagram) {
setStationDiagram({});
return;
}
let returnData = {};
Object.keys(trainDiagram).forEach((key) => {
if (trainDiagram[key].match(props.station.Station_JP)) {
returnData[key] = trainDiagram[key];
}
});
console.log(returnData);
setStationDiagram(returnData);
}, [trainDiagram, props.station]);
const getCurrentTrain = () =>
fetch(
"https://train.jr-shikoku.co.jp/g?arg1=train&arg2=train",
HeaderConfig
)
.then((response) => response.json())
.then((d) =>
d.map((x) => ({ num: x.TrainNum, delay: x.delay, Pos: x.Pos }))
)
.then(setCurrentTrain)
.catch((e) => {
console.log(e);
});
useEffect(getCurrentTrain, []);
useInterval(getCurrentTrain, 15000);
const getTime = (stationDiagram, station) => {
console.log(stationDiagram);
const returnData = Object.keys(stationDiagram).map((d) => {
let a = {}; let a = {};
stationDiagram[d].split("#").forEach((data) => { stationDiagram[d].split("#").forEach((data) => {
if (data.match("着")) { if (data.match("着")) {
a.lastStation = data.split(",着,")[0]; a.lastStation = data.split(",着,")[0];
} }
if (data.match(props.station.Station_JP)) { if (data.match(station.Station_JP)) {
if (data.match(",発,")) { if (data.match(",発,")) {
a.time = data.split(",発,")[1]; a.time = data.split(",発,")[1];
} else { } else {
@ -116,9 +131,9 @@ export default function LED_vision(props) {
} }
} }
}); });
returnData.push({ train: d, time: a.time, lastStation: a.lastStation }); return { train: d, time: a.time, lastStation: a.lastStation };
}); });
console.log(returnData);
return returnData.sort((a, b) => { return returnData.sort((a, b) => {
switch (true) { switch (true) {
case parseInt(a.time.split(":")[0]) < parseInt(b.time.split(":")[0]): case parseInt(a.time.split(":")[0]) < parseInt(b.time.split(":")[0]):
@ -132,23 +147,14 @@ export default function LED_vision(props) {
} }
}); });
}; };
const trainTimeAndNumber = stationDiagram != null ? getTime() : null;
const getCurrentTrain = () =>
fetch(
"https://train.jr-shikoku.co.jp/g?arg1=train&arg2=train",
HeaderConfig
)
.then((response) => response.json())
.then((d) =>
d.map((x) => ({ num: x.TrainNum, delay: x.delay, Pos: x.Pos }))
)
.then(setCurrentTrain);
const [trainTimeAndNumber, setTrainTimeAndNumber] = useState(null);
useEffect(() => { useEffect(() => {
getCurrentTrain(); if (objectIsEmpty(stationDiagram)) return () => {};
}, []); console.log(stationDiagram);
const getTimeData = getTime(stationDiagram, props.station);
useInterval(getCurrentTrain, 15000); setTrainTimeAndNumber(getTimeData);
}, [stationDiagram]);
const timeFiltering = (d) => { const timeFiltering = (d) => {
const date = new Date(); const date = new Date();
@ -188,24 +194,7 @@ export default function LED_vision(props) {
marginHorizontal: wp("1%"), marginHorizontal: wp("1%"),
}} }}
> >
<View <Header />
style={{
alignContent: "center",
alignItems: "center",
width: "100%",
marginVertical: 10,
flexDirection: "row",
}}
>
<View style={{ flex: 1 }}></View>
<View style={{}}>
<Text style={{ fontSize: 25, color: "white", fontWeight: "bold" }}>
次の列車
</Text>
<Text style={{ fontSize: 15, color: "white" }}>Next Train</Text>
</View>
<View style={{ flex: 1 }}></View>
</View>
{trainTimeAndNumber {trainTimeAndNumber
? currentTrain && ? currentTrain &&
trainTimeAndNumber trainTimeAndNumber
@ -214,96 +203,8 @@ export default function LED_vision(props) {
.filter((d) => !!finalSwitch || d.lastStation != "当駅止") .filter((d) => !!finalSwitch || d.lastStation != "当駅止")
.map((d, index) => { .map((d, index) => {
const train = customTrainDataDetector(d.train); const train = customTrainDataDetector(d.train);
return [ return (
<View <>
style={{
alignContent: "center",
alignItems: "center",
width: "94%",
marginVertical: 5,
marginHorizontal: "3%",
backgroundColor: "#000",
flexDirection: "row",
}}
key={d.train}
>
<View style={{ flex: 9 }}>
<Text
style={{
fontSize: train.trainName.length > 6 ? 15 : 20,
color: getTrainType(train.type).color,
fontWeight: "bold",
}}
>
{trainIDSwitch
? d.train
: getTrainType(train.type).name +
" " +
train.trainName +
(train.trainNumDistance == undefined
? ""
: parseInt(
d.train.replace("M", "").replace("D", "")
) -
train.trainNumDistance +
"号")}
</Text>
</View>
<View style={{ flex: 4, flexDirection: "row" }}>
<Text
style={{
fontSize: d.lastStation.length > 4 ? 15 : 20,
color: "white",
fontWeight: "bold",
}}
>
{d.lastStation}
</Text>
</View>
<View style={{ flex: 3 }}>
<Text
style={{
fontSize: 20,
color: "white",
fontWeight: "bold",
}}
>
{d.time}
</Text>
</View>
<View style={{ flex: 4 }}>
<Text
style={{
fontSize: 20,
color: "white",
fontWeight: "bold",
}}
>
{(() => {
const current = currentTrain.filter(
(a) => a.num == d.train
)[0];
const delay = current.delay;
switch (true) {
case delay == "入線":
if (current.Pos == props.station.Station_JP) {
return "当駅始発";
} else {
return "発車前";
}
case isNaN(delay):
return delay;
case delay == 0:
return "定刻通り";
default:
return delay + "分遅れ";
}
})()}
</Text>
</View>
</View>,
trainDescriptionSwitch && !!train.info && (
<View <View
style={{ style={{
alignContent: "center", alignContent: "center",
@ -314,67 +215,237 @@ export default function LED_vision(props) {
backgroundColor: "#000", backgroundColor: "#000",
flexDirection: "row", flexDirection: "row",
}} }}
key={d.train}
> >
<View style={{ flex: 4 }}> <TrainName
<Text train={train}
style={{ trainIDSwitch={trainIDSwitch}
fontSize: 20, d={d}
color: "green", getTrainType={getTrainType(train.type)}
fontWeight: "bold", />
}} <LastStation d={d} />
> <DependTime d={d} />
{" "} <StatusAndDelay
&gt; {train.info} currentTrain={currentTrain}
</Text> d={d}
</View> props={props}
/>
</View> </View>
), {trainDescriptionSwitch && !!train.info && (
]; <Description train={train} key={d.train + "Description"} />
)}
</>
);
}) })
: null} : null}
<View style={{ flexDirection: "row", padding: 10 }}> <Footer
<Text trainIDSwitch={trainIDSwitch}
style={{ setTrainIDSwitch={setTrainIDSwitch}
alignItems: "center", trainDescriptionSwitch={trainDescriptionSwitch}
alignContent: "center", setTrainDescriptionSwitch={setTrainDescriptionSwitch}
textAlign: "center", finalSwitch={finalSwitch}
textAlignVertical: "center", setFinalSwitch={setFinalSwitch}
color: "white", />
}}
>
種別名 / 列番
</Text>
<Switch value={trainIDSwitch} onValueChange={setTrainIDSwitch} />
<View style={{ flex: 1 }} />
<Text
style={{
alignItems: "center",
alignContent: "center",
textAlign: "center",
textAlignVertical: "center",
color: "white",
}}
>
列車情報
</Text>
<Switch
value={trainDescriptionSwitch}
onValueChange={setTrainDescriptionSwitch}
/>
<View style={{ flex: 1 }} />
<Text
style={{
alignItems: "center",
alignContent: "center",
textAlign: "center",
textAlignVertical: "center",
color: "white",
}}
>
当駅止表示
</Text>
<Switch value={finalSwitch} onValueChange={setFinalSwitch} />
</View>
</View> </View>
); );
} }
const Header = () => (
<View
style={{
alignContent: "center",
alignItems: "center",
width: "100%",
marginVertical: 10,
flexDirection: "row",
}}
>
<View style={{ flex: 1 }}></View>
<View style={{}}>
<Text style={{ fontSize: 25, color: "white", fontWeight: "bold" }}>
次の列車
</Text>
<Text style={{ fontSize: 15, color: "white" }}>Next Train</Text>
</View>
<View style={{ flex: 1 }}></View>
</View>
);
const Footer = ({
trainIDSwitch,
setTrainIDSwitch,
trainDescriptionSwitch,
setTrainDescriptionSwitch,
finalSwitch,
setFinalSwitch,
}) => {
return (
<View style={{ flexDirection: "row", padding: 10 }}>
<Text
style={{
alignItems: "center",
alignContent: "center",
textAlign: "center",
textAlignVertical: "center",
color: "white",
}}
>
種別名 / 列番
</Text>
<Switch value={trainIDSwitch} onValueChange={setTrainIDSwitch} />
<View style={{ flex: 1 }} />
<Text
style={{
alignItems: "center",
alignContent: "center",
textAlign: "center",
textAlignVertical: "center",
color: "white",
}}
>
列車情報
</Text>
<Switch
value={trainDescriptionSwitch}
onValueChange={setTrainDescriptionSwitch}
/>
<View style={{ flex: 1 }} />
<Text
style={{
alignItems: "center",
alignContent: "center",
textAlign: "center",
textAlignVertical: "center",
color: "white",
}}
>
当駅止表示
</Text>
<Switch value={finalSwitch} onValueChange={setFinalSwitch} />
</View>
);
};
const TrainName = ({ train, trainIDSwitch, d, getTrainType }) => {
const { trainName, trainNumDistance } = train;
let TrainNumber = "";
if (trainNumDistance != undefined) {
const timeInfo =
parseInt(d.train.replace("M", "").replace("D", "")) - trainNumDistance;
TrainNumber = timeInfo + "号";
}
return (
<View style={{ flex: 9 }}>
<Text
style={{
fontSize: trainName.length > 6 ? 15 : 20,
color: getTrainType.color,
fontWeight: "bold",
}}
>
{trainIDSwitch
? d.train
: `${getTrainType.name} ${trainName}${TrainNumber}`}
</Text>
</View>
);
};
const LastStation = ({ d }) => {
return (
<View style={{ flex: 4, flexDirection: "row" }}>
<Text
style={{
fontSize: d.lastStation.length > 4 ? 15 : 20,
color: "white",
fontWeight: "bold",
}}
>
{d.lastStation}
</Text>
</View>
);
};
const DependTime = ({ d }) => {
return (
<View style={{ flex: 3 }}>
<Text
style={{
fontSize: 20,
color: "white",
fontWeight: "bold",
}}
>
{d.time}
</Text>
</View>
);
};
const StatusAndDelay = ({ currentTrain, d, props }) => {
const [status, setStatus] = useState("");
useEffect(() => {
const current = currentTrain.filter((a) => a.num == d.train)[0];
const delay = current.delay;
switch (true) {
case delay === "入線":
if (current.Pos === props.station.Station_JP) {
setStatus("当駅始発");
break;
} else {
setStatus("発車前");
break;
}
case isNaN(delay):
setStatus(delay);
break;
case delay === 0:
setStatus("定刻通り");
break;
default:
setStatus(delay + "分遅れ");
break;
}
}, []);
return (
<View style={{ flex: 4 }}>
<Text
style={{
fontSize: 20,
color: "white",
fontWeight: "bold",
}}
>
{status}
</Text>
</View>
);
};
const Description = ({ train }) => {
return (
<View
style={{
alignContent: "center",
alignItems: "center",
width: "94%",
marginVertical: 5,
marginHorizontal: "3%",
backgroundColor: "#000",
flexDirection: "row",
}}
>
<View style={{ flex: 4 }}>
<Text
style={{
fontSize: 20,
color: "green",
fontWeight: "bold",
}}
>
{" "}
&gt; {train.info}
</Text>
</View>
</View>
);
};

3
lib/objectIsEmpty.js Normal file
View File

@ -0,0 +1,3 @@
export const objectIsEmpty = (obj) => {
return !Object.keys(obj).length;
};