Skip to content

Commit

Permalink
refactor: Router updating on readme.MD.
Browse files Browse the repository at this point in the history
  • Loading branch information
JoseAlvesdev committed Sep 8, 2024
1 parent 6e88a52 commit 99bd065
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 30 deletions.
63 changes: 37 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,39 +119,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[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 @@ -168,36 +174,41 @@ 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 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) {
navigateTo(linkUrl);
}
// Navega para o novo hash
if (`#${linkUrl}` !== currentUrl) navigateTo(linkUrl);
}
});

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

Expand Down
4 changes: 0 additions & 4 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,3 @@ document.addEventListener('DOMContentLoaded', (): void => {

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




0 comments on commit 99bd065

Please sign in to comment.