Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/use strict #964

Closed
wants to merge 7 commits into from
Closed

Fix/use strict #964

wants to merge 7 commits into from

Conversation

pau-sala-at-wiris
Copy link
Contributor

Description

  • Add strict: true to the tsconfig.json file in the viewer package to enforce stricter typing. This will lead to more robust code and help catch potential bugs at compile time.

Steps to reproduce

Dev deployment

  • Check the dev deploy here, it should show the demo viewer and work as expected.

Locally

  • run: nx build viewer && nx start html-viewer, the code should compile and work as expected

Warning

  • Setting strict to true has revealed a number of errors. Resolving some of these is innocuous, but addressing others involves assumptions that are not clear about what the code should do in certain cases.

#taskid X (Waiting for the card to be created)

@pau-sala-at-wiris pau-sala-at-wiris changed the base branch from stable to master May 16, 2024 15:48
Comment on lines 44 to 48

// Not sure if this should return or continue
if(node.nodeValue === null) {
return;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esto no me atrevería a hacerlo porque no sabemos qué consecuencias podría tener. En todo caso, sugiero que la linea siguiente tuviera algo como:

if(node.nodeValue !== null) {
   node.nodeValue = node.nodeValue.substring(pos, nextLatexPosition.start);
} 

de esta forma el linter se queda satisfecho y no "rompemos" nada porque el bucle seguiería haciendo sus cosas (de lo contrario no me terminaría de quedar tranquilo).

@@ -124,7 +124,7 @@ async function setImageProperties(properties: Properties, data: FormulaData, mml
const { text } = await mathml2accessible(mml, properties.lang, properties.editorServicesRoot, properties.editorServicesExtension);
data.alt = text;
}
img.alt = data.alt;
img.alt = data.alt || '';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Se recomienda en estos casos usar este otro operador https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing

Suggested change
img.alt = data.alt || '';
img.alt = data.alt ?? '';

Comment on lines 26 to 29
/** Sets all fields and subfields of Config mandatory*/
type MandatoryConfig = {
[K in keyof Config]-?: Required<Config[K]>;
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dado que aparentemente Config solo se usa dentro de este fichero de propiedades, creo que podríamos evitarnos esto y simplemente hacer que la interfaz `Config contenga solo campos obligatorios!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Si esa interfaz no se exporta y no queda expuesta al usuario no le veo problema.
Además hay algo raro que no había visto, en la declaración de la clase Properties:

config: Config = defaultValues; 

Aquí ya se asignan los default values, no entiendo porque en los getters no se devuelve eso directamente.
Lo cambio, si más adelante vemos que hay que exponer eso ya lo cambiaremos.

}

Properties.instance.checkServices();
Properties.instance?.checkServices();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esta comprobación no es necesaria gracias a la que hay al principio de la función.


node.textContent = node.textContent.substring(0,start) + node.textContent.substring(end + endMathmlTag.length);
node.textContent = (node.textContent?.substring(0,start) as string) + node.textContent?.substring(end + endMathmlTag.length);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Este as string creo que está camuflando un error diferente al esperado, ya que si lo elimino me dice el linter que Object is possibly 'undefined'. Quizás aquí deberíamos ver qué pasa en esos casos donde los textContent son undefined?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Si, ese y algún otro de los puntos que has comentado son los que me daban miedo. Yo sólo haría un casting si es evidente que es correcto, en ese caso no es evidente que lo sea.
Por otro lado, sin el strict aquí en tiempo de ejecución habría petado con un cannot read properties of undefined al hacer el substring, con lo que para respetar lo que había antes habría que lanzar un error si el textContent no existe.
Imagino que la solución pasa por evaluar bien el código y definir si esa ausencia de textContent es un error (y lanzamos un error), o no puede darse nunca (y hacemos el casting) o es algo controlado y se define un default que tenga sentido en ese contexto.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

De todos modos, desde mi punto de vista, ese tipo de funciones son super candidatas a tener unos test unitarios que contemplen esos casos para ahorrarnos ese tipo de cuestiones en un futuro.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

De acuerdo con lo de las pruebas unitarias, pero no se hasta qué punto son viables debido a que dependenden de nodos que no se hasta qué punto es fácil replicar en un entorno de pruebas o no 🤔

Copy link
Contributor

@jgonzalez-at-wiris jgonzalez-at-wiris left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Genial trabajo, gracias por tomarte el tiempo de mejorar estos detalles!

Doy el aprobado a nivel de código pero me gustaría que esto lo probáramos a nivel de comportamiento, es decir, ejecutar el código y verificar que todo sigue funcionando igual. Por favor @carla-at-wiris @usantos-at-wiris ¿podriais revisar y ayudar a verificar esto que comento? Gracias!

Copy link
Contributor

@usantos-at-wiris usantos-at-wiris left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The creation of this branch was from main and not from master. Please change.

Copy link
Contributor

@carla-at-wiris carla-at-wiris left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given the fact that the branch was originally created from main, there are many conflicts with the modified files, and the staging demo breaks when trying to render new formulas. This last point may be solved if the code aligns with the current master.

@pau-sala-at-wiris
Copy link
Contributor Author

Given the fact that the branch was originally created from main, there are many conflicts with the modified files, and the staging demo breaks when trying to render new formulas. This last point may be solved if the code aligns with the current master.

Given the scope and size of the PR I've created a new one from master branch to avoid conflict related issues . We should close this and review the other one.

@pau-sala-at-wiris pau-sala-at-wiris deleted the fix/use-strict branch May 21, 2024 06:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants