Skip to content

Commit

Permalink
added rootPropsListeners to state; RouteLink using Link to avoid refr…
Browse files Browse the repository at this point in the history
…eshing the browser; Router now supports Link, routeBlocked prop and old config var removed, SimpleRouter removed.
  • Loading branch information
wpdas committed Apr 10, 2024
1 parent 6eb8f9e commit 5cd06a3
Show file tree
Hide file tree
Showing 9 changed files with 61 additions and 100 deletions.
11 changes: 0 additions & 11 deletions lib/alem-vm/alem-vm.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,16 +87,6 @@ type LinkProps = {
params?: Record<string, any>;
};

type URLRouterProps = {
routes: Route[];
/**
* Parameter name to store current route name. Default is "path".
*/
parameterName?: string;
};

export declare const SimpleRouter: (props: URLRouterProps) => JSX.Element;

/**
* Link to access routes.
*/
Expand Down Expand Up @@ -185,7 +175,6 @@ export type UseRoutesProps = {
routeParameterName: string;
routes: string[];
routeType: string;
routeBlocked: boolean;
routeParams: Record<string, any>;
history: string[];
};
Expand Down
11 changes: 5 additions & 6 deletions lib/alem-vm/importable/RouteLink.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
// NOTA: Arquivo original antes da descoberta e uso do `Link`
// `Link` não está sendo usado pois falha quando se tentar voltar ou ir pra frente
// usando os botoes do navegador

import { LinkProps, navigate, useContext } from "../alem-vm";

/**
Expand Down Expand Up @@ -45,8 +41,11 @@ export const RouteLink = ({
});
}

// Evita o refresh da pagina
const Link = styled("Link")``;

return (
<a
<Link
onClick={onClickHandler}
className={className}
style={{ cursor: "pointer", textDecoration: "none", ...style }}
Expand All @@ -58,7 +57,7 @@ export const RouteLink = ({
}
>
{label || children}
</a>
</Link>
);
}

Expand Down
31 changes: 18 additions & 13 deletions lib/alem-vm/importable/Router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,24 @@ const Router = (props: RouterProps) => {
const { routeParameterName, routeType, activeRoute } = alemRoutes;
const routeParamName = parameterName || routeParameterName;

// Registra como listener das props do root
useEffect(() => {
const handler = (data: any) => {
const _type = type || "URLBased";
if (_type === "URLBased") {
alemRoutes.updateRouteParameters({
activeRoute: data[routeParamName],
});
}
};

alem.registerListenerHandler(handler);

return () => {
alem.unregisterListenerHandler();
};
}, []);

const checkIfPathIsIncludedToRoutes = (routePath: string) => {
let pathFound = false;
if (routes) {
Expand All @@ -65,10 +83,6 @@ const Router = (props: RouterProps) => {
// BOS.props
const bosProps = alem.rootProps;

// ContentBased config only: should maintain the current route over refreshes?
const maintainRoutesWhenDeveloping =
alem.isDevelopment && alem.alemConfig_maintainRouteWhenDeveloping;

if (routes) {
// Check if currentUrlPath exists in the routes list, if not, use
// the first element's path
Expand All @@ -85,14 +99,6 @@ const Router = (props: RouterProps) => {
let _activeRoute =
initialRoute || alemRoutes.activeRoute || currentUrlPath;

if (
!(currentUrlPath && routeType == "URLBased" && alemRoutes.routeBlocked)
) {
_activeRoute = maintainRoutesWhenDeveloping
? initialRoute || activeRoute
: routes[0].path;
}

// Checa se o config.keepRoute esta ativado e se tiver, se tem uma rota salva
let _activeRouteParams = null;
let _history = null;
Expand All @@ -119,7 +125,6 @@ const Router = (props: RouterProps) => {
activeRoute: _activeRoute,
routeParams: _activeRouteParams,
history: _history,
routeBlocked: true,
routeParameterName: routeParamName,
});
}
Expand Down
17 changes: 8 additions & 9 deletions lib/alem-vm/importable/RouterContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import {
const ALEM_ROUTES_CONTEXT_KEY = "alemRoutes";

const RouterContext = () => {
const { setDefaultData, updateData } = createContext(ALEM_ROUTES_CONTEXT_KEY);
const { setDefaultData, updateData, getSelf } = createContext<any>(
ALEM_ROUTES_CONTEXT_KEY,
);

/**
* Update the alem state
Expand All @@ -37,7 +39,6 @@ const RouterContext = () => {
routeParameterName: "path",
routes: [] as string[],
routeType: "URLBased", // URLBased | ContentBased
routeBlocked: true, // Used to force navigate to other paths even when the "path=" parameter is present into the URL

// ==================================== Routes - Methods ====================================

Expand All @@ -48,7 +49,6 @@ const RouterContext = () => {
routes?: string[];
routeType?: RouteType;
activeRoute?: string;
routeBlocked?: boolean;
routeParams?: Record<string, any>;
history?: History[]; // Previous history if config.keepRoute is true
routeParameterName?: string;
Expand Down Expand Up @@ -79,13 +79,12 @@ const RouterContext = () => {
}

updateAlemRoutesState({
routes: routeProps.routes || alemRoutesState().routes,
routeType: routeProps.routeType || alemRoutesState().routeType,
activeRoute: routeProps.activeRoute || alemRoutesState().activeRoute,
routeBlocked: routeProps.routeBlocked || alemRoutesState().routeBlocked,
routeParams: routeProps.routeParams || alemRoutesState().routeParams,
routes: routeProps.routes || getSelf().routes,
routeType: routeProps.routeType || getSelf().routeType,
activeRoute: routeProps.activeRoute || getSelf().activeRoute,
routeParams: routeProps.routeParams || getSelf().routeParams,
routeParameterName:
routeProps.routeParameterName || alemRoutesState().routeParameterName,
routeProps.routeParameterName || getSelf().routeParameterName,
history: updatedHistory,
routesInitialized: true,
});
Expand Down
40 changes: 0 additions & 40 deletions lib/alem-vm/importable/SimpleRouter.tsx

This file was deleted.

14 changes: 13 additions & 1 deletion lib/alem-vm/importable/navigate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useContext } from "../alem-vm";
import { isDevelopment, useContext } from "../alem-vm";

const navigate = {
/**
Expand All @@ -12,6 +12,12 @@ const navigate = {
console.error("navigate is being used without Router on top of it.");
}

if (isDevelopment && routeContext.routeType === "URLBased") {
console.warn(
'The route type is "URLBased", "navigate" should only be used with the "ContentBased" type.',
);
}

if (routeContext.routes.includes(route)) {
// Precia enviar toda a estrura ja existente e atualizar somente o recurso desejado.
// Isso se deve devido a quando se altera um state, o componente onde ele está é
Expand All @@ -34,6 +40,12 @@ const navigate = {
console.error("navigate is being used without Router on top of it.");
}

if (isDevelopment && routeContext.routeType === "URLBased") {
console.warn(
'The route type is "URLBased", "navigate" should only be used with the "ContentBased" type.',
);
}

const updatedHistory = routeContext.history;
if (updatedHistory) {
updatedHistory.pop();
Expand Down
17 changes: 17 additions & 0 deletions lib/alem-vm/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,19 @@ const alemState = () => state.alem as typeof AlemStateInitialBody.alem;

const AlemStateInitialBody = {
alem: {
// System to send root properties to listeners
rootPropsListeners: [],
registerListenerHandler: (handler: (data: any) => void) => {
if (!props.alem.rootPropsListeners.includes(handler)) {
props.alem.rootPropsListeners.push(handler);
}
},
unregisterListenerHandler: (handler: (data: any) => void) => {
props.alem.rootPropsListeners = props.alem.rootPropsListeners.filter(
(item) => item !== handler,
);
},

ready: false,
/**
* Root project props
Expand Down Expand Up @@ -212,6 +225,10 @@ if (props.alem.keepRoute) {
});
}

// Chama todos os metodos guardados no alem.handlers quando a propriedade
// do root mudar
props.alem.rootPropsListeners.forEach((handler) => handler(props));

export type Alem = any;

// TODO: (Store -> Ser usar persistencia) Load previous store
11 changes: 0 additions & 11 deletions lib/config/importableAlemFileSchemas.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,6 @@ const importableAlemFileSchemas = () => {
path.join(__dirname, "../", ALEM_VM_FOLDER, "importable", "getLocation.ts"),
);

const simpleRouterSchema = transformFileToFileSchema(
path.join(
__dirname,
"../",
ALEM_VM_FOLDER,
"importable",
"SimpleRouter.tsx",
),
);

const createDebounceSchema = transformFileToFileSchema(
path.join(
__dirname,
Expand Down Expand Up @@ -117,7 +107,6 @@ const importableAlemFileSchemas = () => {
routeLinkSchema,
useRoutesSchema,
getLocationSchema,
simpleRouterSchema,
createDebounceSchema,
navigateSchema,
modulesContextSchema,
Expand Down
9 changes: 0 additions & 9 deletions lib/config/importableFiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,6 @@ const getLocation = path.join(
"getLocation.ts",
);

const SimpleRouter = path.join(
__dirname,
"../",
ALEM_VM_FOLDER,
"importable",
"SimpleRouter.tsx",
);

const createDebounce = path.join(
__dirname,
"../",
Expand Down Expand Up @@ -133,7 +125,6 @@ module.exports = {
RouteLink,
useRoutes,
getLocation,
SimpleRouter,
createDebounce,
navigate,
ModulesContext,
Expand Down

0 comments on commit 5cd06a3

Please sign in to comment.