Style-dictionary – Design tokens to scss mixins as css

my challange is that I want to make export from json to the scss mixins that will have css variables in it.

I’m getting json from figma(token studio) in the structure of tokens/designSystem/semantic.json,core.json, and token/designSystem/components/[anyComponent]

I have exported that is creating scss styles from this json, but I need to make mixins with css variables

This is my buildStyleDictionary.mjs:

import StyleDictionary from "style-dictionary";
import { readFile, readdir, rm } from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const configPath = path.join(__dirname, "config.json");
const config = JSON.parse(await readFile(configPath, "utf-8"));

const buildDir = path.join(__dirname, "style-dictionary");

// Remove the existing build directory to prevent duplicates
await rm(buildDir, { recursive: true, force: true });

// Register filters for each foundation type based on $type or prefix in semantic.json and core.json
const foundationTypes = [
  "color",
  "elevation",
  "size",
  "border",
  "font",
  "line",
  "spacing",
];
foundationTypes.forEach((type) => {
  StyleDictionary.registerFilter({
    name: `is${type.charAt(0).toUpperCase() + type.slice(1)}Token`,
    filter: (token) =>
      token.$type === type ||
      ((token.filePath.includes("semantic.json") ||
        token.filePath.includes("core.json")) &&
        token.name.startsWith(`${type}-`)),
  });
});

// Function to dynamically generate component-specific SCSS files
async function getComponentFiles() {
  const componentDir = path.join(__dirname, "tokens/designSystem/Component");
  const componentFiles = await readdir(componentDir);
  return componentFiles.map((file) => ({
    destination: `Component/${file.replace(".json", ".scss")}`,
    format: "scss/variables",
    filter: {
      filePath: `tokens/designSystem/Component/${file}`,
    },
  }));
}

const componentFiles = await getComponentFiles();

const sd = new StyleDictionary({
  ...config,
  platforms: {
    ...config.platforms,
    scss: {
      ...config.platforms.scss,
      files: [
        // Generate semantic and core as whole files without filtering by type
        {
          destination: "semantic.scss",
          format: "scss/variables",
          filter: {
            filePath: "tokens/designSystem/semantic.json",
          },
        },
        {
          destination: "core.scss",
          format: "scss/variables",
          filter: {
            filePath: "tokens/designSystem/core.json",
          },
        },
        // Generate foundation files in the Foundations folder
        ...foundationTypes.map((type) => ({
          destination: `Foundations/${type}.scss`,
          format: "scss/variables",
          filter: `is${type.charAt(0).toUpperCase() + type.slice(1)}Token`,
        })),
        // Component-specific files
        ...componentFiles,
      ],
    },
  },
});

sd.buildAllPlatforms();

console.log(
  "Style Dictionary build completed with semantic, core, Foundations, and Component SCSS files.",
);

Config.json:

  "source": [
    "./tokens/SignFace/semantic.json",
    "./tokens/SignFace/core.json",
    "./tokens/SignFace/Component/*.json"
  ],
  "platforms": {
    "scss": {
      "transformGroup": "scss",
      "buildPath": "style-dictionary/"
    },
    "css": {
      "transformGroup": "css",
      "buildPath": "style-dictionary/css/",
      "files": [
        {
          "destination": "variables.css",
          "format": "css/variables"
        }
      ]
    }
  }
}

Structure after export
Structure after the export

Result

$label-font-family: Hind;
$label-font-weigth: 500;
$label-line-height: 100%;
$label-font-size: 14;
$label-text-base: #333e4a;
$label-gap: 4px;
$label-icon-size: 16px;
$label-icon-border-width: 1px; 

Expected Result

@mixin reset-list {
  --label-font-family: Hind;
  --label-font-weigth: 500;
  --label-line-height: 100%;
  --label-font-size: 14;
  --label-text-base: #333e4a;
  --label-gap: 4px;
  --label-icon-size: 16px;
  --label-icon-border-width: 1px; 
} 

Uploading image to S3 from user-submitted form completes but corrupted

In a Remix app, I have a form I’m using to select & upload an image, just a simple <input name="image" type="file" />

The form POSTs to a Remix handler, and in the handler (see code below) I’m trying to upload this image to Amazon S3 using the v3 SDK. I’ve tried with both the PutObjectCommand from client-s3 and with Upload from lib-storage – same result…

The upload “works” – It successfully creates the file in the bucket. I can see the filesize matches exactly what I expect when I upload the same file directly into the S3 bucket via the web UI.

However as an “image” the file doesn’t open. Something seems to be either corrupted, or created in a way that the file is not recognized as an image.


In the handler, I get the file data as an AsyncIterable<Uint8Array> and the only real processing I’m doing is to convert that into a single Uint8Array for the Upload.

Is there something wrong with my conversion to a Uint8Array or is there a more correct way to convert that for the upload, maybe a different type?

Or something else I need to configure in the way I’m setting the upload to S3?

async ({ name, contentType, data, filename }) => {
  const arrayOfUInt8Array: Uint8Array[] = [];

  let length = 0;
  for await (const x of data)
  {
    arrayOfUInt8Array.push(x);
    length += x.length;
  }

  const file = new Uint8Array(length);

  for (const x of arrayOfUInt8Array) {
    file.set(x);
  }

  const buff = Buffer.from(file);

  const uploadCommand = new Upload({
    client: s3Client,
    params: {
      Bucket: s3Bucket,
      Key: filename,
      Body: buff,
      ContentType: contentType,
    }
  });

  await uploadCommand.done();

  return '';
},

react electron importing ‘execa’ Error: Can’t resolve ‘child_process’

I have been dealing with this issue for a while, trying different stackoverflow solutions, AI advice, multiple re-writes, and I am still very puzzles by it.

I have a react electron app, which works fine, but if I try to import the ‘execa’ module:

import { execa } from 'execa';

I always get these error messages:

[0] Failed to compile.
[0] 
[0] Module not found: Error: Can't resolve 'child_process' in '/home/martin/Documents/projects/electron-ghactions/node_modules/cross-spawn'
[0] ERROR in ./node_modules/cross-spawn/index.js 3:11-35
[0] Module not found: Error: Can't resolve 'child_process' in '/home/martin/Documents/projects/electron-ghactions/node_modules/cross-spawn'
[0] 
[0] ERROR in ./node_modules/cross-spawn/lib/parse.js 3:13-28
[0] Module not found: Error: Can't resolve 'path' in '/home/martin/Documents/projects/electron-ghactions/node_modules/cross-spawn/lib'
[0] 
[0] BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
[0] This is no longer the case. Verify if you need this module and configure a polyfill for it.
[0] 
[0] If you want to include a polyfill, you need to:
[0]     - add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
[0]     - install 'path-browserify'
[0] If you don't want to include a polyfill, you can use an empty module like this:
[0]     resolve.fallback: { "path": false }
[0] 

It happens when I try to import execa at this line in my file ‘FFmpeg.js’ inside of this repo:
https://github.com/MartinBarker/electron-ghactions/blob/e76d643302cdc8601c11877eff8b43f2d5977c65/src/Ffmpeg.js#L3

The thing that confuses me, is that I have a separate repo doing a very similar thing, react and electron, which can import and use this line totally fine with no error:

const execa = window.require('execa');

https://github.com/MartinBarker/RenderTune/blob/59450b3f8445731e419c99335e7ebf7dbca6cbdf/src/FFmpeg.js#L4C1-L4C39

I’ve tried taking all the dependency versions from the working repo package.json and moving them to my non working repo, but the error still persists. Is there a config setting inside my electron-ghactions repo package.json file causing this error? How can I allow for the importing of execa inside my react component FFmpeg.js ?

how to change background for each called month in calendar

i’m using the semantic calendar from https://fullcalendar.io and i am trying to have the background for each month change. i have not been able to find how to do this as the code looks like it calls them up via math calculations. is there a way to add javascript to look for the info in the h2 code and compare it, if it’s january XXXX then background is background.png?

here is the calendar being called in html, as you cann see it;s just calling the js function so i cant alter anything here

 <div id='calendar' style="background-image: url('assets/images/pgs/month01.png'); background-size: 100%; background-repeat: no-repeat; width: 81.5%;  z-index: 8; position:relative; float: right;"></div>

this is the code on the page inspect after it’s run:

<h2 class="fc-toolbar-title" id="fc-dom-1">January 2024</h2>

maybe the js is editable but i think it’s best to just add a new script on the html page that reads the info ad changes it that way?

i think this is part of the js that calls the month:

function Tl(e,t){for(let n in e)console.warn(Unknown option '${n}'+(t? for view '${t}':""))}class _l extends Xn{render(){return g("div",{className:"fc-toolbar-chunk"},...this.props.widgetGroups.map(e=>this.renderWidgetGroup(e)))}renderWidgetGroup(e){let{props:t}=this,{theme:n}=this.context,r=[],i=!0;for(let s of e){let{buttonName:e,buttonClick:o,buttonText:l,buttonIcon:a,buttonHint:c}=s;if("title"===e)i=!1,r.push(g("h2",{className:"fc-toolbar-title",id:t.titleId},t.title));else{let i=e===t.activeButton,s=!t.isTodayEnabled&&"today"===e||!t.isPrevEnabled&&"prev"===e||!t.isNextEnabled&&"next"===e,d=[fc-${e}-button,n.getClass("button")];i&&d.push(n.getClass("buttonActive")),r.push(g("button",{type:"button",title:"function"==typeof c?c(t.navUnit):c,disabled:s,"aria-pressed":i,className:d.join(" "),onClick:o},l||(a?g("span",{className:a,role:"img"}):"")))}}if(r.length>1){return g("div",{className:i&&n.getClass("buttonGroup")||""},...r)}return r[0]}}

so if anyone can help, i’m drawing a blank on how to call the function to look at the title and then change the background for it. maybe an array would work? i’m just lost atm, any help would be great.

Data Lost Between Routes in Vue.js on Refresh

I’m working on a Vue.js application using Vue Router and Axios to fetch user data. I have two pages: /dashboard and /dashboard/me. The data for the /dashboard page is successfully loaded and displayed, even after refreshing. However, when I navigate to /dashboard/me and refresh the page, I lose the data from Dashboard components (Dashboard is a wrapper for all children routes), and the request results in a 304 Not Modified status code.

Here’s what I’ve tried:

Vue Router setup: The routes are defined as follows:

const routes: RouteRecordRaw[] = [
    {
        path: '/dashboard, component: Dashboard, name: 'dashboard',
        children: [{ path: 'me', name: 'me', component: AboutMePage }],
    },
];

I initially had the me route defined as path: ‘me’ (relative), but when I change it to path: ‘/me’ (absolute), the page works correctly on refresh, but the issue is that now the route becomes /dashboard and /me instead of /dashboard/me.

Axios request: I’m using Axios to fetch data, and it works fine on the /dashboard route. On the /dashboard/me route, however, when I refresh the page, I get a 304 Not Modified response, which causes the data to be lost.

The request code is as follows:

const { data, isLoading, refetch } = useGetUserQuery(userId, {
    onSuccess: (user) => {
        toast.add({
            severity: 'success',
            summary: `Welcome, ${user.email}`,
            life: 3000,
        });
    },
    onError: (error) => {
        toast.add({
            severity: 'error',
            summary: error?.message[0],
            life: 3000,
        });
    },
});

The refetch function is also used to refresh the data.

Proxy configuration in Vite: I have configured a proxy in my vite.config.ts file to redirect requests to the backend server.

export default defineConfig({
  plugins: [vue()],
  server: {
    proxy: {
      '/v1': {
        target: 'http://localhost:3001/',
        changeOrigin: true,
        secure: false,
        ws: true,
        configure: (proxy, _options) => {
          proxy.on('error', (err, _req, _res) => {
            console.log('proxy error', err);
          });
          proxy.on('proxyReq', (proxyReq, req, _res) => {
            console.log('Sending Request to the Target:', req.method, req.url);
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('Received Response from the Target:', proxyRes.statusCode, req.url);
          });
        },
      }
    }
  }
})

Problem:

When I refresh the /dashboard/me page, I get an empty response and the data is lost.
The network response shows 304 Not Modified, but on the /dashboard page, it works fine and I get the correct data.

What I’ve tried:

Changing the route path from relative (‘me’) to absolute (‘/me’), which made the page work, but broke the URL structure.
Using Cache-Control: no-cache headers in Axios, but still getting the 304 response.
Clearing the browser cache and testing in incognito mode, but the issue persists.

Questions:

Why does changing the route path (‘me’ to ‘/me’) affect the behavior of the data fetching?

Why does the request for /dashboard work fine, but /dashboard/me loses the data upon page refresh?

How can I fix the issue and ensure that I always fetch fresh data without altering the URL structure?

Any help would be greatly appreciated!

How to Dynamically Load and Manage Plugins in a JavaScript Application?

I’m working on a JavaScript application and would like to implement a plugin system. The idea is to allow developers to extend the app’s functionality by creating plugins that can be loaded at runtime.

Here’s what I’ve done so far:

Created a basic plugin interface where each plugin exports a set of predefined methods.
Used require() for local plugins during development.
However, I’m facing challenges:

Dynamically loading plugins, especially from remote URLs.
Preventing plugins from interfering with the core application or each other.
What I’ve Tried:
Looked into using import() for dynamic imports but ran into cross-origin restrictions when trying to load plugins from external sources.
Experimented with an iframe sandbox for isolation, but this approach makes communication between the app and plugins tricky.
Specific Questions:
What’s the best way to dynamically load and safely execute JavaScript plugins from external sources?
Are there tools or libraries in the JavaScript ecosystem that simplify this process?
How can I manage plugin dependencies to ensure they don’t conflict with the main app or other plugins?
I’d appreciate concrete examples or best practices for implementing this kind of system. click for more detail

How to get the zip code using the new Google map Places API Autocomplete (New)?

I’m trying to get a list of addresses from USA with autocomplete search with the help of the new Google maps places api (Autocomplete endpoint).

This is what I tried to do to get it but it’s not include the zip code:

const fetchPlaces = async (inputValue: string) => {
    if (!inputValue) return;

    const response = await fetch(
      `https://places.googleapis.com/v1/places:autocomplete`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-Goog-Api-Key": process.env.NEXT_PUBLIC_GOOGLE_API_KEY || "",
        },
        body: JSON.stringify({
          input: inputValue,
          includedRegionCodes: ["us"],
        }),
      }
    );
    return await response.json();
  };

What I’m missing here? I didn’t find anything about the zip code on the docs.

Angular and RxDB infinite loop

In the component I have a simple table were one of the columns calls a function getOrderItems() to get order corresponding items:

<p-table
  [value]="orders$()"
  [tableStyle]="{ 'min-width': '50rem', 'margin-top': '16px' }"
>
  <ng-template pTemplate="header">
    <tr>
      <th>Id</th>
      <th>Contact</th>
      <th>Total</th>
      <th>Status</th>
      <th>Item</th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-order>
    <tr>
      <td>{{ order.id }}</td>
      <td>{{ order.contact }}</td>
      <td>{{ order.total }}</td>
      <td>{{ order.status }}</td>
      <td>{{ getOrderItems() }}</td>
    </tr>
  </ng-template>
</p-table>

Here is the getOrderItems() function:

getOrderItems() {
    const orderItems = this.ordersService.orderItems();

    console.log(orderItems);
    return orderItems;
  }

Finallt here is the function inside ordersService:

orderItems() {
    let orderItems: OrderItem[] = [];
    this.databaseService
      .getDatabase()
      .orderItem.find()
      .exec()
      .then((doc) => {
        orderItems.push(doc);
      })
      .catch((e: RxError) => {
        return Promise.reject(
          'Error while looking for order items: ' + e.message,
        );
      });

    return orderItems;
  }

The issue I’m getting infinite loop because of getOrderItems() function and I have no idea why?

Unable to Reproduce Bug and Suggestions for a Simple, Reproducible Issue to Work On [closed]

I am currently working on identifying bugs in the following repository: mozilla/gecko-dev. I searched for bugs using Bugzilla with filters such as product=Firefox and component=General, although other filters might also apply. This search led me to several bugs.

One of the simpler bugs I found is Bug 698732. To test it, I opened a sample video (link to the video) in the Firefox browser on my Windows 11 system and pressed the Esc key. However, I couldn’t reproduce the issue described in the bug.

I’m currently facing two challenges and would appreciate help:

  1. Why is the above bug not reproducible? Am I missing any setup or context?
  2. Could you suggest a defect that is simpler to work on and reproducible? I’m struggling to identify a suitable bug.

How can I implement a “Flash in” animation in javascript?

Currently I have a div that has the class “hidden” (css, display: none). I want it to add the class “full-size” after a set ammount of time with javascript. However, how can I implement a “flash in” function?

setTimeout(fade_out, 28000);

function fade_out() {
    $("#interval").fadeOut().empty();
}

window.setTimeout(function() {
    $("#main").fadeIn().addClass('full-size');
}, 28000);

Instead of “fadeIn()”, is there something similar that gives a “White flash in” animation where it flashes you with a white color and then the white color fades out to reveal “#main”?

Sorry if this request is unreasonable, this’ll be my first time asking a question instead of using AI!! Figured that it might be a good opportunity 😀

I tried searching on google but really could’nt find what I was searching for.
The best I got was a “repetitivily flashing, blinking” animation:

$("#someElement").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);

Which isnt what I was searching for 🙁

Line not appearing on line chart only y-axis and x-axis appear in d3.js linechart

I am trying to create a line graph in d3.js but only my axes are appearing; the line doesn’t show.

I think there might be something wrong with how i use the nest but i don’t have any idea how to fix it.

This is the current state of what my code shows when execute
enter image description here

Here is the snippet of the code and i use d3 ver 3

  // Define line generator function for Weekday Sales chart
  var lineWeekday = d3.svg.line()
    .x(function(d) { return xWeekday(d.key); })
    .y(function(d) { return yWeekday(d.value); });

  // Render Weekday Sales chart
  var xWeekday = d3.scale.ordinal().domain(totalSalesByWeekday.map(function(d) { return d.key; }))
    .rangeRoundBands([0, width], 0.1);
  var yWeekday = d3.scale.linear().domain([0, d3.max(totalSalesByWeekday, function(d) { return d.value; })])
    .range([height, 0]);

  // Render Weekday Sales line chart
  svgWeekday.append("path")
    .data(totalSalesByWeekday)
    .attr("class", "line-weekday")
    .attr("d", function(d){return lineWeekday (d);})
    .attr("fill", "none")
    .attr("stroke", "blue")
    .attr("stroke-width", 2);
  
  svgWeekday.append("g")
    .attr("class", "x-axis")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.svg.axis().scale(xWeekday).orient("bottom"));

  svgWeekday.append("g")
    .attr("class", "y-axis")
    .call(d3.svg.axis().scale(yWeekday).orient("left"));

I had tried to make it into array by adding [] in the .data but it gives me error so i’m stuck

TypeScript: Enforcing PK Type Consistency with Defined Keysets in Generic Interfaces

// interfaces.tsx
interface User {
  id: number | string;
  name: string | null;
}

// keysets.tsx
const userPK = ["id"];


// store.tsx
interface StoreState<T, PK extends Extract<keyof T, string | number>> {
  data: T
  update(pk: Pick<T, PK>, updatedItem: Partial<T>);
}

If I write this way, update’s first argument requires both id and name. How can I enforece PK to be whatever defined in userPK?

Removing the default variation alert with inline alert message in Woocommerce

I’m trying to remove the default variation popup alert message with an inline alert instead in Woocommerce.

in the (class-wc-fronted-script.php) here is the code I have:

case 'wc-add-to-cart-variation':
// We also need the wp.template for this script :).
wc_get_template( 'single-product/add-to-cart/variation.php' );

$params = array(
    'wc_ajax_url'                      => WC_AJAX::get_endpoint( '%%endpoint%%' ),
    'i18n_no_matching_variations_text' => esc_attr__( 'Sorry, no products matched your selection. Please choose a different combination.', 'woocommerce' ),
    'i18n_make_a_selection_text'       => esc_attr__( 'Please select some product options before adding this product to your cart.', 'woocommerce' ),
    'i18n_unavailable_text'            => esc_attr__( 'Sorry, this product is unavailable. Please choose a different combination.', 'woocommerce' ),
);
break;

Any suggestions?

Thanks!

I tried this function:

add_action('wp_enqueue_scripts', function () {
    // Remove WooCommerce's add-to-cart variation script
    wp_dequeue_script('wc-add-to-cart-variation');
}, 100);

but with no luck

Why isnt page.evaluate() function code being executed within async function? – Puppeteer

const getLastCarData = async (page, make) => {
  let sort = ascending;
  let url = `https://www.xxxxxxxxxxxxx/xxxxxxxxx?make=${make}&postcode=XXXXXXX&sort=${sort}`;
  // await page.goto(url, { waitUntil: 'networkidle0' });
  await page.goto(url, { waitUntil: 'domcontentloaded' });
  await goToPageWithRetries(page, url); // more robust


  // ERROR FINDING LAST CAR
  // Returning false value
//   const html = await page.content();
//   console.log(html);

    
  console.log("Before page.evaluate");

  const lastCar = await page.evaluate( () => {
      console.log("inside page.evaluate");
      const carPods = Array.from(document.querySelectorAll('[data-testid="trader-seller-listing"], [data-testid="private-seller-listing"]'));
      const nonPromotedCars = carPods.filter(car => 
          !car.querySelector('[data-testid="leasing-listing-details"]') && 
          !car.querySelector('[data-testid="LEASING_LISTING"]') &&
          !car.querySelector('a[href*="journey=PROMOTED_LISTING_JOURNEY"]')
      );
      
      if (nonPromotedCars.length === 0) {
          console.log("No non-promoted cars found on this page.");
          return null;
      }

      const convertPrice = (priceString) => {
          return parseFloat(priceString.replace('£', '').replace(/,/g, ''));
      };

      let lowestPriceCar = null;
      let lowestPrice = Infinity;

      nonPromotedCars.forEach(car => {
          const priceElement = car.querySelector('div div div section section div p span span');
          if (priceElement) {
              const price = convertPrice(priceElement.innerText);
              if (price < lowestPrice) {
                  lowestPrice = price;
                  lowestPriceCar = {
                      listingId: car.getAttribute('id'),
                      price: price
                  };
              }
          }
      });

      return lowestPriceCar;
  });

  if ( lastCar) {
      const finalListingPath = path.join('tempData', `finalListing${make}.json`);
      await fs.writeFile(finalListingPath, JSON.stringify(lastCar, null, 2));
      console.log(`Final listing for ${make} saved to ${finalListingPath}. Lowest price: ${lastCar.price}`);
  } else {
      console.log(`No valid cars found for ${make}`);
  }

  return lastCar;
};

The code within the page.evaluate function is not being executed at all.

Expected: to return the price value of the last item on the page

Instead, the code is not executed and therefore the lastCar variable stays null which leads to the logic error of printing “No valid cars” when there are.