Pick-A-Brick LDraw Colors

Replaces LEGO color names with LDraw color names on Pick a Brick

  1. // ==UserScript==
  2. // @name Pick-A-Brick LDraw Colors
  3. // @name:en Pick-A-Brick LDraw Colors
  4. // @description Replaces LEGO color names with LDraw color names on Pick a Brick
  5. // @namespace Violentmonkey Scripts
  6. // @match https://www.lego.com/en-us/pick-and-build/pick-a-brick*
  7. // @grant none
  8. // @version 1.2.1
  9. // @author The0x539
  10. // @run-at document-start
  11. // @license AGPL-3.0
  12. // ==/UserScript==
  13. /* jshint esversion: 11 */
  14.  
  15. const gistUrl = "https://gist.githubusercontent.com/The0x539/d046e6778f38232912c6ca1d840d614e/raw";
  16. const colorMapPromise = fetch(gistUrl).then(resp => resp.json()).then(body => new Map(body));
  17.  
  18. const actualFetch = window.fetch;
  19. window.fetch = async (...args) => {
  20. const response = await actualFetch(...args);
  21. if (args[0] !== 'https://www.lego.com/api/graphql/PickABrickQuery') {
  22. return response;
  23. }
  24.  
  25. const body = await response.json();
  26. const colorMap = await colorMapPromise;
  27. replaceNames(body, colorMap);
  28.  
  29. // Reconstruct the response because we already consumed the body of the original response object.
  30. const { status, statusText, headers } = response;
  31. const options = { status, statusText, headers };
  32. return new Response(JSON.stringify(body), options);
  33. };
  34.  
  35. function replaceNames(body, colorMap) {
  36. for (const facet of body.data.searchElements.facets) {
  37. if (facet.id !== "element.facet.colourFamily") {
  38. continue;
  39. }
  40.  
  41. for (const label of facet.labels) {
  42. for (const child of label.children) {
  43. if (colorMap.has(child.key)) {
  44. child.name = colorMap.get(child.key);
  45. }
  46. }
  47. }
  48. }
  49.  
  50. for (const result of body.data.searchElements.results) {
  51. const colorFacet = result.facets.color;
  52. if (colorMap.has(colorFacet.key)) {
  53. colorFacet.name = colorMap.get(colorFacet.key);
  54. }
  55. }
  56. }