Skip to content

Commit

Permalink
Extract hook functions to individual files
Browse files Browse the repository at this point in the history
  • Loading branch information
loicfrance committed Feb 26, 2024
1 parent 7a837c2 commit 4b119df
Show file tree
Hide file tree
Showing 20 changed files with 104 additions and 76 deletions.
3 changes: 2 additions & 1 deletion src/components/ConfigLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import ConfigGameTab from './config/ConfigGameTab'
import ConfigAudioTab from './config/ConfigAudioTab'
import ConfigAdvancedTab from '../components/config/ConfigAdvancedTab'
import ConfigControlsTab from '../components/config/ConfigControlsTab'
import strings, { useLanguageRefresh } from '../utils/lang'
import strings from '../utils/lang'
import TabsComponent from './molecules/TabsComponent'
import { SCREEN } from '../utils/display'
import MenuButton from './atoms/MenuButton'
import { useLanguageRefresh } from './hooks/useLanguageRefresh'

enum Tabs {
game = "Game",
Expand Down
3 changes: 2 additions & 1 deletion src/components/config/ConfigAdvancedTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import { ConfigButtons, ConfigItem, ResetBtn } from "../ConfigLayout"
import { defaultSettings, settings } from "../../utils/variables"
import { deepAssign, jsonDiff, requestJSONs, textFileUserDownload } from "../../utils/utils"
import { SaveState, clearSaveStates, listSaveStates, restoreSaveStates } from "../../utils/savestates"
import strings, { addLang, languages, useLanguageRefresh } from "../../utils/lang"
import strings, { addLang, languages } from "../../utils/lang"
import { RecursivePartial } from "../../types"
import { RxExternalLink } from 'react-icons/rx'
import { toast } from "react-toastify"
import { useLanguageRefresh } from "../hooks/useLanguageRefresh"

function twoDigits(n: number) {
return n.toString().padStart(2, '0')
Expand Down
3 changes: 2 additions & 1 deletion src/components/config/ConfigAudioTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { useEffect, useState } from "react"
import { ConfigButtons, ConfigItem, ResetBtn } from "../ConfigLayout"
import { defaultSettings, settings } from "../../utils/variables"
import { deepAssign, negative } from "../../utils/utils"
import strings, { useLanguageRefresh } from "../../utils/lang"
import strings from "../../utils/lang"
import { MdOutlineVolumeOff, MdOutlineVolumeUp, MdVolumeMute } from "react-icons/md"
import { useLanguageRefresh } from "../hooks/useLanguageRefresh"

const ConfigAudioTab = () => {
useLanguageRefresh()
Expand Down
3 changes: 2 additions & 1 deletion src/components/config/ConfigControlsTab.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Fragment, useRef } from "react"
import { KeymapKeyFilter, inGameKeymap } from "../../utils/KeyMap"
import strings, { useLanguageRefresh } from "../../utils/lang"
import strings from "../../utils/lang"
import { bb } from "../../utils/Bbcode"
import { useLanguageRefresh } from "../hooks/useLanguageRefresh"

type KeyMapEntry = [string, typeof inGameKeymap[keyof typeof inGameKeymap]]

Expand Down
3 changes: 2 additions & 1 deletion src/components/config/ConfigGameTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { ViewRatio } from "../../types"
import { TEXT_SPEED } from "../../utils/constants"
import { addEventListener, deepAssign, isFullscreen, toggleFullscreen } from "../../utils/utils"
import { FaMinus, FaPlus } from "react-icons/fa"
import strings, { useLanguageRefresh } from "../../utils/lang"
import strings from "../../utils/lang"
import { useLanguageRefresh } from "../hooks/useLanguageRefresh"

const ConfigGameTab = () => {
useLanguageRefresh()
Expand Down
12 changes: 12 additions & 0 deletions src/components/hooks/useLanguageRefresh.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { useReducer } from "react";
import { useObserver } from "../../utils/Observer";
import { strings } from "../../utils/lang";

/**
* To use in components.
* Forces a refresh of the component when the language is loaded.
*/
export function useLanguageRefresh() {
const [_updateNum, forceUpdate] = useReducer(x => (x + 1) % 100, 0);
useObserver(forceUpdate, strings, 'translation-name')
}
19 changes: 19 additions & 0 deletions src/components/hooks/useScreenAutoNavigate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useEffect } from "react"
import { useNavigate } from "react-router-dom"
import { observe, unobserve } from "../../utils/Observer"
import { SCREEN, displayMode } from "../../utils/display"

/**
* Navigate to the correct screen when setting the `displayMode.screen` value.
* Sets this attribute to the provided `currentScreen`.
* @param currentScreen label of the current screen this hook is used on
*/
export function useScreenAutoNavigate(currentScreen: SCREEN) {
const navigate = useNavigate()
useEffect(()=> {
displayMode.screen = currentScreen
observe(displayMode, 'screen', navigate,
{ filter: (s)=> s != currentScreen })
return unobserve.bind(null, displayMode, 'screen', navigate) as VoidFunction
}, [])
}
25 changes: 25 additions & 0 deletions src/components/hooks/useTraceUpdate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useRef, useEffect } from "react";

/**
* Prints the changes in the provided properties everytime the component updates.
* The logs are outputed using the function `console.debug()`.
* @param prefix prefix to print before the changes in the output
* @param props Properties to watch
*/
export function useTraceUpdate(prefix: string, props: Record<string, any>) {
const prev = useRef(props);
useEffect(() => {
const changedProps = Object.entries(props).reduce((ps, [k, v]) => {
if (prev.current[k] !== v) {
ps[k] = [prev.current[k], v];
}
return ps;
}, {} as Record<string, any>);
if (Object.keys(changedProps).length > 0) {
console.debug(prefix, 'Changed props:', changedProps);
} else {
console.debug(prefix, 'No changed props');
}
prev.current = props;
});
}
5 changes: 3 additions & 2 deletions src/screens/ConfigScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import '../styles/config.scss'
import { SCREEN, displayMode, useScreenAutoNavigate } from '../utils/display'
import { SCREEN, displayMode } from '../utils/display'
import { motion } from 'framer-motion'
import { useLanguageRefresh } from '../utils/lang'
import ConfigLayout from '../components/ConfigLayout'
import { useScreenAutoNavigate } from '../components/hooks/useScreenAutoNavigate'
import { useLanguageRefresh } from '../components/hooks/useLanguageRefresh'

const ConfigScreen = () => {
useScreenAutoNavigate(SCREEN.CONFIG)
Expand Down
3 changes: 2 additions & 1 deletion src/screens/DisclaimerScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { useEffect } from 'react'
import '../styles/title-menu.scss'
import { motion } from 'framer-motion'
import { useNavigate } from 'react-router-dom'
import strings, { useLanguageRefresh } from '../utils/lang'
import strings from '../utils/lang'
import { bb } from '../utils/Bbcode'
import { useLanguageRefresh } from '../components/hooks/useLanguageRefresh'

const DisclaimerScreen = () => {
const navigate = useNavigate()
Expand Down
6 changes: 4 additions & 2 deletions src/screens/EndingsScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import '../styles/endings.scss'
import { motion } from 'framer-motion'
import strings, { imageUrl, useLanguageRefresh } from '../utils/lang'
import { SCREEN, useScreenAutoNavigate } from '../utils/display'
import strings, { imageUrl } from '../utils/lang'
import { SCREEN } from '../utils/display'
import chalkboard from '../assets/images/chalkboard.webp'
import { noBb } from '../utils/Bbcode'
import { RouteEnding, endings, osiete } from '../utils/endings'
import { Tooltip } from 'react-tooltip'
import ReactDOMServer from 'react-dom/server';
import { playScene } from '../utils/savestates'
import MenuButton from '../components/atoms/MenuButton'
import { useLanguageRefresh } from '../components/hooks/useLanguageRefresh'
import { useScreenAutoNavigate } from '../components/hooks/useScreenAutoNavigate'

// settings.completedScenes.push("s521")
const EndingsScreen = () => {
Expand Down
6 changes: 4 additions & 2 deletions src/screens/FlowchartScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { motion } from "framer-motion"
import '../styles/saves.scss'
import { SCREEN, displayMode, useScreenAutoNavigate } from "../utils/display"
import strings, { useLanguageRefresh } from "../utils/lang"
import { SCREEN, displayMode } from "../utils/display"
import strings from "../utils/lang"
import { Flowchart } from "../components/Flowchart"
import MenuButton from "../components/atoms/MenuButton"
import { useLanguageRefresh } from "../components/hooks/useLanguageRefresh"
import { useScreenAutoNavigate } from "../components/hooks/useScreenAutoNavigate"

const FlowchartScreen = () => {
useScreenAutoNavigate(SCREEN.SCENES)
Expand Down
6 changes: 4 additions & 2 deletions src/screens/GalleryScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import '../styles/gallery.scss'
import { settings } from '../utils/variables'
import { motion } from 'framer-motion'
import { CharacterId, GALLERY_IMAGES, GalleryImg } from '../utils/gallery'
import strings, { imageUrl, useLanguageRefresh } from '../utils/lang'
import { SCREEN, useScreenAutoNavigate } from '../utils/display'
import strings, { imageUrl } from '../utils/lang'
import { SCREEN } from '../utils/display'
import TabsComponent from '../components/molecules/TabsComponent'
import MenuButton from '../components/atoms/MenuButton'
import { useLanguageRefresh } from '../components/hooks/useLanguageRefresh'
import { useScreenAutoNavigate } from '../components/hooks/useScreenAutoNavigate'

type GalleryItem = GalleryImg & {src_thumb: string, src_hd: string}

Expand Down
5 changes: 3 additions & 2 deletions src/screens/LoadScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { motion } from "framer-motion"
import '../styles/saves.scss'
import SavesLayout from "../components/SavesLayout"
import { SCREEN, displayMode, useScreenAutoNavigate } from "../utils/display"
import { useLanguageRefresh } from "../utils/lang"
import { SCREEN, displayMode } from "../utils/display"
import { useLanguageRefresh } from "../components/hooks/useLanguageRefresh"
import { useScreenAutoNavigate } from "../components/hooks/useScreenAutoNavigate"

const LoadScreen = () => {
useScreenAutoNavigate(SCREEN.LOAD)
Expand Down
6 changes: 4 additions & 2 deletions src/screens/TitleMenuScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,22 @@ import moon from "../assets/images/moon.webp"
import tsukiR from "../assets/images/tsukihime_blue_glass_cover.webp"
import '../styles/title-menu.scss'
import ParticlesComponent from '../components/molecules/ParticlesComponent'
import { SCREEN, displayMode, useScreenAutoNavigate } from '../utils/display'
import { SCREEN, displayMode } from '../utils/display'
import { motion } from 'framer-motion'
import { blankSaveState, getLastSave, hasSaveStates, loadSaveFiles, loadSaveState, loadScene } from '../utils/savestates'
import history from '../utils/history'
import Modal from 'react-modal';
import { APP_VERSION } from '../utils/constants'
import strings, { useLanguageRefresh } from '../utils/lang'
import strings from '../utils/lang'
import { bb } from '../utils/Bbcode'
import { useObserved } from '../utils/Observer'
import { MdGetApp, MdInfoOutline, MdLink } from 'react-icons/md'
import { settings } from '../utils/variables'
import { endings } from '../utils/endings'
import { toast } from 'react-toastify'
import MenuButton from '../components/atoms/MenuButton'
import { useLanguageRefresh } from '../components/hooks/useLanguageRefresh'
import { useScreenAutoNavigate } from '../components/hooks/useScreenAutoNavigate'

type BeforeInstallPromptEvent = Event & {prompt: ()=>Promise<{outcome: any}>}

Expand Down
5 changes: 3 additions & 2 deletions src/screens/Window.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@ import { HiMenu } from 'react-icons/hi';
import GestureHandler from '../utils/touch';
import { toast } from 'react-toastify';
import { useObserved } from '../utils/Observer';
import { SCREEN, displayMode, isViewAnyOf, useScreenAutoNavigate } from '../utils/display';
import { SCREEN, displayMode, isViewAnyOf } from '../utils/display';
import { KeysMatching } from '../types';
import { useLanguageRefresh } from '../utils/lang';
import ConfigLayer from '../layers/ConfigLayer';
import { moveBg } from '../utils/graphics';
import { useLanguageRefresh } from '../components/hooks/useLanguageRefresh';
import { useScreenAutoNavigate } from '../components/hooks/useScreenAutoNavigate';

//##############################################################################
//# USER INPUTS #
Expand Down
11 changes: 0 additions & 11 deletions src/utils/display.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,17 +194,6 @@ export function isViewAnyOf(...views: Array<typeof displayMode.currentView>) {
return views.includes(displayMode.currentView)
}

export function useScreenAutoNavigate(currentScreen: SCREEN) {
const navigate = useNavigate()
useEffect(()=> {
displayMode.screen = currentScreen
observe(displayMode, 'screen', navigate,
{ filter: (s)=> s != currentScreen })
return unobserve.bind(null, displayMode, 'screen', navigate) as VoidFunction
}, [])
}


//##############################################################################
//# DEBUG #
//##############################################################################
Expand Down
23 changes: 10 additions & 13 deletions src/utils/graphics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,22 +54,19 @@ export function extractImage(image: string) {
export function getTransition(type: string, skipTransition = false) {
let duration = 0
let effect = type
let speed: string|null

if (effect.startsWith('type_'))
if (effect.startsWith('type_')) {
effect = effect.substring('type_'.length)

const index = effect.lastIndexOf('_')
if (index !== -1) {
if (!skipTransition) {
let speed = effect.substring(index+1)
switch(speed) {
case 'slw': duration = 1500; break
case 'mid': duration = 800; break
case 'fst': duration = 400; break
default : throw Error(`Ill-formed effect '${effect}'`)
}
}
[effect, speed] = splitLast(effect, '_')
if (speed != null && !skipTransition) {
switch(speed) {
case 'slw': duration = 1500; break
case 'mid': duration = 800; break
case 'fst': duration = 400; break
default : throw Error(`Ill-formed effect '${type}'`)
}
effect = effect.substring(0, index)
}
return {effect, duration}
}
Expand Down
9 changes: 0 additions & 9 deletions src/utils/lang.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,6 @@ export async function waitLanguageLoad() {
})
}

/**
* To use in components.
* Forces a refresh of the component when the language is loaded.
*/
export function useLanguageRefresh() {
const [_updateNum, forceUpdate] = useReducer(x => (x + 1) % 100, 0);
useObserver(forceUpdate, strings, 'translation-name')
}

export default strings

//_________________________translation-related getters__________________________
Expand Down
24 changes: 1 addition & 23 deletions src/utils/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -351,26 +351,4 @@ export function isIterable(obj: any): obj is Iterable<any> {
return typeof obj[Symbol.iterator] === 'function'
}

export function TSForceType<T>(_v: any): asserts _v is T {}

//##############################################################################
//# DEBUG #
//##############################################################################

export function useTraceUpdate(before: string, props: Record<string, any>) {
const prev = useRef(props);
useEffect(() => {
const changedProps = Object.entries(props).reduce((ps, [k, v]) => {
if (prev.current[k] !== v) {
ps[k] = [prev.current[k], v];
}
return ps;
}, {} as Record<string, any>);
if (Object.keys(changedProps).length > 0) {
console.debug(before, 'Changed props:', changedProps);
} else {
console.debug(before, 'No changed props');
}
prev.current = props;
});
}
export function TSForceType<T>(_v: any): asserts _v is T {}

0 comments on commit 4b119df

Please sign in to comment.