Saltar al contenido principal

Introducción al Historial de API (GSoC 2024)

· 8 lectura mínima

Los cambios históricos en las API de Electron ahora serán detallados en los documentos.


Hola 👋, soy Peter, el 2024 Google Summer of Code (GSoC) colaborador de Electron.

Durante el curso del programa GSoC, implementé una función de historial de API para la documentación de Electron y sus funciones, clases, etc. de forma similar a la Nodo. s documentación: permitiendo el uso de un esquema YAML simple pero potente en los archivos Markdown de documentación de la API y mostrándolo bien en el sitio web de documentación de Electron.

Detalles

Sistema de documentación del historial de API / esquema YAML

En la documentación de Markdown API, el historial de una función/clase/etc. ahora se coloca justo después de la cabecera para ese elemento en forma de un bloque de código YAML encapsulado por un comentario HTML.

#### `win.setTrafficLightPosition(position)` _macOS_

<!--
```YAML history
añadido:
- pr-url: https://github. om/electron/electron/pull/22533
cambia:
- pr-url: https://github.com/electron/electron/pull/26789
description: "Made `trafficicLightPosition` option work for `customButtonOnHover` window.
obsoleto:
- pr-url: https://github. om/electron/electron/pull/37094
breaking-changes-header: deprecated-browserwindowsettrafficiclightpositionposition
```
-->

* `position` [Point](structures/point.md)

Establecer una posición personalizada para los botones de semáforo. Sólo se puede usar con `titleBarStyle` establecido en `hidden`.

Creo que usar YAML como los documentos Node.js lo hacen era el mejor enfoque porque es fácil de leer. El historial de la API no es extremadamente complicado y idealmente debería ser tan fácil de escribir y leer como sea posible.

El diseño final que se muestra anteriormente es en realidad significativamente diferente al que he propuesto:

<!--
```YAML history
added: v10.0.0
deprecated: v25.0.0
removed: v28.0.0
changes:
- version: v13.0.0
pr-url: https://github.com/electron/electron/pull/26789
description: Made `trafficLightPosition` option work for `customButtonOnHover` window.
```
-->

Un gran cambio es la retirada de números de versión:

"[...] Hay un cambio algo significativo que nos gustaría llamar sobre la propuesta, que surgió durante el debate cuando estábamos revisando las propuestas. [...]

[we] decided that the approach with the [fewest] drawbacks would be to only use PR URLs (the root PRs to main) instead of hardcoded version strings as in the proposal.

This can serve as a single source of truth which can then be used to derive exact version numbers, and no further documentation changes on main are necessary if the change is backported to other branches."

— David Sanders (@dsanders11) via Slack

We also didn't include removals in the API History, since when an API is removed from Electron, it is also removed from the documentation.

JavaScript implementation

I originally planned to create a new @electron/docs-api-history-tools npm package that would contain scripts for extracting, validating/linting and converting the API history in the documentation files.

About a week before the coding period began, and after some discussion with my mentors, I realized that was probably unnecessary:

"Hi everyone, I was thinking about the project after our huddle: Considering that extraction logic will have to be handled differently in e/website and e/lint-roller because of their dependencies, maybe there is no need for a separate package for API history stuff?"

ProposedRevised
proposedrevised

— Piotr Płaczek (me) via Slack

We ultimately decided to not go ahead with my original idea:

"@Piotr Płaczek that seems fine to me! I think we can always refactor out to a separate module in a later iteration if we find that we need to share a lot of code between the two implementations anyways 🙂"

— Erick Zhao (@erickzhao) via Slack

Instead, we divided those various tools across the Electron repos that were most relevant to them:

UI and styling for Electron documentation website

I originally proposed a simple table to display the API History data:

Design Prototype (Closed)Design Prototype (Open)
demo1demo2

Así es como se ve el diseño implementado final:

demo3

Pretty al igual que el prototipo. La adición más significativa es el uso de SemVer rangos, que fueron elegidos para comunicar mejor en qué versiones está presente una característica (gracias Samuel Attard (@MarshallOfSound) por la sugerencia!).

Esto es importante porque los cambios son frecuentemente portados a través de líneas de lanzamiento de Electron soportadas. una corrección puede hacerlo en Electron v32.0.0, v31.1.0 y v30.2.0. Esto significa que no está presente en la v31.0. que un usuario podría deducir por error del hecho de que está presente en una versión v30.x.x.

Guía de uso/estilo

I added a usage/style guide dedicated to writing API history documentation for new features. I described proper usages of the YAML schema in detail, provided typical/useful examples, etc. You can find it here.

Migration guide

Since existing APIs have to be migrated to the new documentation system, I created a migration guide. It features the typical steps of what a developer has to do when migrating old APIs: looking through breaking changes, browsing through the past releases, maybe looking through old commits, etc. Then instructing the developer to follow the usage/style guide to add API history documentation for each previously existing class/function/etc.

Sadly, I couldn't think of a way to automate this effectively. This would probably be a great task for an AI/ML engineer; however, I don't possess those skills and was too afraid of accidentally introducing hallucinations into the API history. Even if automated, the information would still probably have to be verified by a human in the end 😕. This task will probably have to be done manually, on a file-by-file basis, just like it was done for the Node.js documentation.

Deliverables

  • api-history.schema.json

  • lint-markdown-api-history.ts

    • Script for linting YAML API history written according to a custom YAML (technically JSON) schema.
      • Useful error messages
      • Comprehensive documentation / code comments
      • Extensive Jest Vitest tests
      • Good performance
    • Implemented in: electron/lint-roller#73
    • Used in: electron/electron#42982
  • preprocess-api-history.ts

    • Performs simple validation just in case incorrect API History manages to make it into the repo. Also strips the HTML comment tags that wrap API History blocks since Docusaurus cannot parse them.
    • Implemented/Used in: electron/website#594
  • transformers/api-history.ts

    • Script for converting YAML API history blocks in the Markdown documentation files to Markdown/HTML React tables (ApiHistoryTable.tsx).
    • Implemented/Used in: electron/website#594
  • ApiHistoryTable.tsx

    • React table component used to display parsed API History data on the documentation website.
      • Uses styling that follows the rest of the website's design.
      • Responsive, accessible, and generally well written HTML, CSS, and JS.
    • Implemented/Used in: electron/website#594
  • styleguide.md

    • Usage/style guide section for new API history documentation system.
      • Easy to understand
      • Well written
      • Includes examples
    • Implemented/Used in: electron/electron#42982
  • api-history-migration-guide.md

    • Migration guide for new API history documentation system.
      • Easy to understand
      • Well written
      • Includes examples
    • Implemented/Used in: electron/electron#42982

Conclusión

I had a lot of fun working on this feature and was able to earn valuable experience from code reviews and discussing its various implementation details with the team.

I believe the addition of API history to the documentation will make the lives of developers using Electron a lot easier, especially ones attempting to migrate their existing app from a several year old Electron version.

I also want to sincerely thank my mentors:

...and the rest of the Electron team for answering my questions and taking the time to give me feedback on my pull requests. It is very much appreciated.