I am working on a custom font feature where the user can upload a .css file and use it in our editor. In order to do show I need to know the font-weight present in the file, so that I can display them in the dropdown list in the editor.
Please suggest a best way to figure out the font-weight available for the custom font. As user will be uploading the file, therefore I wont be aware of the font-weights.
User Input:
/* latin */
@font-face {
font-family: 'Poppins';
font-style: italic;
font-weight: 200;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v20/pxiDyp8kv8JHgFVrJJLmv1pVF9eOYktMqg.woff2) format('woff2');
}
/* devanagari */
@font-face {
font-family: 'Poppins';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v20/pxiDyp8kv8JHgFVrJJLm21lVFteOYktMqlap.woff2) format('woff2');
}
/* latin */
@font-face {
font-family: 'Poppins';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v20/pxiGyp8kv8JHgFVrJJLucHtAOvWDSA.woff2) format('woff2');
}
Required Data: [200, 300, 400]
Looking for JS solution.
Thanks @herrstrietzel for the above solution.
Instead of creating a style tag with an id and then disabling it. I have used CSSStyleSheet(). Below is my code.
/**
* this would be css content
* retrieved via fileReader/input
*/
let cssText = `
/* latin */
@font-face {
font-family: 'Poppins';
font-style: italic;
font-weight: 200;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v20/pxiDyp8kv8JHgFVrJJLmv1pVF9eOYktMqg.woff2) format('woff2');
}
/* latin */
@font-face {
font-family: 'Poppins';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v20/pxiGyp8kv8JHgFVrJJLucHtAOvWDSA.woff2) format('woff2');
}
/* latin-ext */
@font-face {
font-family: 'Agdasima';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/agdasima/v2/PN_0Rfyxp2f1fUCgAPCGgCza3v3xzHMj54Y.woff2) format('woff2');
}
`;
let cssSheet = new CSSStyleSheet()
cssSheet.replaceSync(cssText)
let rules = [...cssSheet.cssRules]
let fontProps = []
rules.forEach((rule) => {
let type = rule.type
// type 5 is @font-face
if (type === 5) {
let fontFamily = rule.style.getPropertyValue("font-family")
let fontStyle = rule.style.getPropertyValue("font-style")
let fontWeight = rule.style.getPropertyValue("font-weight")
fontProps.push({
fontFamily: fontFamily,
fontWeight: fontWeight,
fontStyle: fontStyle
})
}
})
console.log(fontProps)