Skip to content

Commit

Permalink
refactor: Hash mode implementation on router, reason: Incompatibility…
Browse files Browse the repository at this point in the history
… issues with GitHub pages.
  • Loading branch information
JoseAlvesdev committed Sep 8, 2024
1 parent 1db443f commit 6e88a52
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 41 deletions.
6 changes: 3 additions & 3 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@
<!-- | Navbar -->
<!-- ============================================================ -->
<max-navbar>
<a class="c-navbar__logo" slot="logo" href="/hbomax/" data-link>
<a class="c-navbar__logo" slot="logo" href="#/" data-link>
<img class="c-navbar__img ts-image-logo" src="/images/hbo-logo.svg" alt="logo da HBOMAX" />
</a>
<a class="c-navbar__link ts-assign-link" slot="link" href="/hbomax/#c-subscription" data-link>assine agora</a>
<a class="c-navbar__link" slot="sign-link" href="/hbomax/signin" data-link>entrar</a>
<a class="c-navbar__link ts-assign-link" slot="link" href="#c-subscription">assine agora</a>
<a class="c-navbar__link" slot="sign-link" href="#/signin" data-link>entrar</a>
</max-navbar>
<!-- ============================================================ -->
<!-- | Loader -->
Expand Down
4 changes: 2 additions & 2 deletions public/views/home.view.html
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ <h3>Mobile</h3>
</li>
</ul>
</div>
<a href="/hbomax/not-implemented" class="c-button c-button--gradient" data-link>
<a href="#/not-implemented" class="c-button c-button--gradient" data-link>
Escolher o Plano Mobile
</a>
</div>
Expand Down Expand Up @@ -113,7 +113,7 @@ <h3>Multitelas</h3>
</li>
</ul>
</div>
<a href="/hbomax/not-implemented" class="c-button c-button--gradient" data-link>
<a href="#/not-implemented" class="c-button c-button--gradient" data-link>
Escolher o Plano Multitelas
</a>
</div>
Expand Down
2 changes: 1 addition & 1 deletion public/views/not-found.view.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<h1 class="c-info__title">404</h1>
<p class="c-info__text">desculpe, mas a página que você solicitou não foi implementada</p>
<div class="c-info__actions">
<a href="/hbomax/" class="c-button c-info__button c-button--gradient" data-link>go home</a>
<a href="#/" class="c-button c-info__button c-button--gradient" data-link>go home</a>
<a href="#" class="c-info__link">contact us</a>
</div>
</div>
Expand Down
4 changes: 2 additions & 2 deletions public/views/signin.view.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ <h1 class="c-login__title">Entrar</h1>
minlength="8"
/>
<div class="c-login__actions">
<a href="/hbomax/not-implemented" class="c-button c-login__button c-button--gradient" data-link>Entrar</a>
<a href="/hbomax/not-implemented" class="c-login__link" data-link> Esqueceu a senha? </a>
<a href="#/not-implemented" class="c-button c-login__button c-button--gradient" data-link>Entrar</a>
<a href="#/not-implemented" class="c-login__link" data-link> Esqueceu a senha? </a>
</div>
</form>
</main>
73 changes: 40 additions & 33 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,45 @@ import getElement from './utils/get-element.util';
import setClasses from './utils/set-classes.util';
import sleep from './utils/sleep.util';

// Base URL
import viteConfig from '../vite.config'

const navigateTo = (url: string): void => {
history.pushState(null, '', url);
window.location.hash = url; // Muda o hash da URL
router();
};

const router: () => Promise<void> = async (): Promise<void> => {
const routes: IRoute[] = [
{ path: "/", view: HomeView },
{ path: "/signin", view: SignInView },
{ path: '/404', view: NotFoundView }
{ path: "#/", view: HomeView },
{ path: "#/signin", view: SignInView },
{ path: '#/404', view: NotFoundView }
];

// Test each route potential match
const potentialMatches: IPotentialMatch[] = routes.map((route: IRoute): IPotentialMatch => {
return {
route: route,
isMatch: location.pathname === `${viteConfig.base.substring(0, 7)}${route.path}`
isMatch: location.hash === route.path // Verifica o hash
}
});

let match: IPotentialMatch | undefined = potentialMatches
.find((potentialMatch: IPotentialMatch): boolean => potentialMatch.isMatch);

if (!match) {
match = {
route: routes.find((route: IRoute): boolean => route.path === '/404') || routes[routes.length - 1],
isMatch: true
};
// Verifica se o hash corresponde a um ID existente
const hashId = location.hash.substring(1);
const element = document.getElementById(hashId);

if (element) {
// Se o ID existir, não redireciona para 404
match = { route: { path: '', view: HomeView }, isMatch: true }; // Usa uma view padrão
} else {
match = {
route: routes.find((route: IRoute): boolean => route.path === '#/404') || routes[routes.length - 1],
isMatch: true
};
}
}

const root: HTMLElement = getElement('#root');
const view = new match.route.view();

Expand All @@ -61,42 +67,43 @@ const router: () => Promise<void> = async (): Promise<void> => {
await sleep(.3);
setClasses(['#root'], false, 'is-show');
}

// Rolagem para o ID especificado no hash
const hash: string = window.location.hash.substring(1); // Remove o '#'

const route: string = match.route.path;
if (hash) {
const element: HTMLElement | null = document.getElementById(hash);

if (route !== '/')
getElement('.ts-assign-link').setAttribute('data-link', '');
else
getElement('.ts-assign-link').removeAttribute('data-link');
if (element) element.scrollIntoView({ behavior: 'smooth' }); // Rola suavemente para o elemento
else console.warn(`Elemento com ID "${hash}" não encontrado.`);
}
}

init();
};

window.addEventListener('popstate', router);
window.addEventListener('hashchange', router); // Escuta mudanças no hash

document.addEventListener('DOMContentLoaded', (): void => {
// Defina o hash padrão se estiver vazio
if (!window.location.hash) window.location.hash = "#/"; // Defina o hash inicial como a página inicial

document.body.addEventListener('click', (e: MouseEvent): void => {
// const exit: () => void = async (): Promise<void> => {
// await sleep(.3);
// setClasses(['#root'], true, 'is-show--exit');
// }

const target = e.target as HTMLElement;

if (target.matches('[data-link]')) {
e.preventDefault(); // Sempre prevenir o comportamento padrão

const currentUrl: string = window.location.href;
const linkUrl: string = (target as HTMLAnchorElement).href;
const currentUrl: string = window.location.hash; // Obtém o hash atual
const linkUrl: string = (target as HTMLAnchorElement).href.split('#')[1]; // Obtém o hash do link

if (currentUrl !== linkUrl) {
//exit();
navigateTo(linkUrl);
}
// Navega para o novo hash
if (`#${linkUrl}` !== currentUrl) navigateTo(linkUrl);
}
});

router();
router(); // Chama o router na inicialização
});




0 comments on commit 6e88a52

Please sign in to comment.