Can't get the glyph code when using gulp-iconfont - css

I'm trying to use gulp-iconfont to build an icon font from a set of svg images.
I've created my gulp task and there're no errors when I run it. But neither can I get the code for each icon, which is what I need to use the icons on css pseudoelements.
The console output shows strange characters where the unicode is supposed to be:
Here's my gulp task:
gulp.task('iconfont', function(){
gulp.src(['assets/icons/*.svg'])
.pipe(iconfont({
fontName: 'icon-font', // required
appendUnicode: true, // recommended option
normalize: true,
centerHorizontally: true,
fontHeight: 100,
formats: ['ttf', 'eot', 'woff'],
}))
.on('glyphs', function(glyphs, options) {
console.log(glyphs, options);
})
.pipe(gulp.dest('assets/fonts/'));
});
As the appendUnicode option is set to true, I can see it at the beggining of my svg file name, for example uEA02-calendar.svg.
However, if I try to use it on my css file:
.calendar:before {
content: "uEA02";
speak: none;
font-style: normal;
font-weight: normal;
font-family: "icon-font"; }
what I see is the text uEA02 instead of my icon. I've checked and the font is loading, I don't know what could I be missing here?

I usually pair gulp-iconfont with gulp-iconfont-css. This additional package exports a stylesheet with the appropriate entities binded to a class. You can export pre-processed css or vanilla css.
Here's my gulp task.
var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');
var glyphFontName = 'icon';
var stream = gulp.src('resources/assets/glyph/*.svg')
.pipe(iconfontCss({
fontName: glyphFontName,
path: 'node_modules/gulp-iconfont-css/templates/_icons.scss',
targetPath: '../../resources/sass/generated/' + glyphFontName + '.scss',
fontPath: '../fonts/',
cssClass: 'i',
centerHorizontally: true
}))
.pipe(iconfont({
fontName: glyphFontName,
formats: [
'ttf',
'eot',
'woff',
'woff2'
],
}))
.pipe(gulp.dest('public/fonts/'));
return stream;

You simply need to escape the unicode string with a backslash (\).
In your CSS just write:
.calendar:before {
content: "\EA02";
speak: none;
font-style: normal;
font-weight: normal;
font-family: "icon-font";
}

You need to reformat the unicode from within the function you're passing to the "on glyphs" event. Otherwise the unicode will be lost in templating.
I'd suggest something like this:
.on('glyphs', function(glyphs, options) {
glyphs = glyphs.map((glyph) => {
...glyph,
unicode: glyph.unicode[0].codePointAt(0).toString(16).toUpperCase()
});
console.log(glyphs, options);
})
Can't take credit for this solution - found the answer in this post

Related

Best practices - Different paths for each environment in styles files

I have a certain frontend code that is deployed in another website through a specific div.
Our assets, like images and such, are made available in different urls, based on the environment (dev, staging and production).
In the code, I used window.location.href to obtain the current url to discover in which environment I am:
export const buildImagePath = (resource_path:string):string => {
var url = window.location.href;
if (url.includes(".staging.") )
return "https://staging.something.com"+"/"+resource_path ;
else #production
return "https://something.com" +"/"+resource_path;
return resource_path;
}
, and then gave each image a class id, and added the following code
ngOnInit(): void {
var imgs =document.getElementsByClassName("img_class_X") as HTMLCollectionOf<HTMLImageElement>| null;
if (imgs!=null)
for(var i = 0; i < imgs.length; i++) {
if (imgs[i]!=null)
imgs[i].src = buildImagePath('assets/imgs/icons/X.svg');
}
}
And this works - except for some hardcoded paths in have in a styles.scss file: urls for website fonts.
How can I had the logic there as well? Meaning, how to make the code conditionally load the fonts from staging.something.com/assets/fonts... or something.com/assets/fonts/... based on the enviroment, for this file:
styles.scss:
/ For more information: https://material.angular.io/guide/theming
#use "~#angular/material" as mat;
$fontpath: "https://something.com/assets/fonts/";
#font-face {
font-family: "my cool font";
src: url($fontpath + "mycoolfont.woff2") format("woff2"),
url($fontpath + "mycoolfont.woff") format("woff");
font-weight: bold;
font-style: normal;
}

How to load cutom fonts such as 'Tondo' using WbfontLoader?

I need to load fonts (.eot,.ttf etc) on demand as per the requirement.
WebFont.load({
custom: {
families: ['Font1'],
urls: ['css-path']
}
});
I am unable to do it using above approach.
One of the solution i found out to create style element and add the #font-face like this -
const cssStr = `
#font-face {
font-family: Tondo;
src: url(../static-assets/common/fonts/tondo/tondo-light-webfont.eot);
}`
const style = document.createElement('style');
style.innerHTML = cssStr;
document.head.appendChild( style );
Is there any better way to do it?

Using fonts in chakra UI in Next js

My application is built using NextJs and uses Chakra UI.
I have installed Google Fonts by following this
chakra Google fonts
npm install #fontsource/open-sans #fontsource/raleway
import { extendTheme } from "#chakra-ui/react"
const theme = extendTheme({
fonts: {
heading: "Open Sans",
body: "Raleway",
},
})
export default theme
Now I can use two different fonts,
For Body
For headings
However, how about using more fonts ?
Say I was to use different fonts for Buttons,
Different for Text.
Also within text, I want to use different fonts for Italic and underlined text portions.
How do I do that ?
It is pretty easy to add more fonts using the theme, you just need to add them in fonts: {} and then you can reference them by using the chakra variable: var(--chakra-fonts-xxx)
For example, if you want to define a font dedicated to subheader:
import { extendTheme } from "#chakra-ui/react";
const theme = extendTheme({
fonts: {
heading: "Open Sans",
subHeading: "Times New Roman",
body: "Arial Black",
},
textStyles: {
h2: {
'font-family': 'var(--chakra-fonts-subHeading)',
},
}
});
export default theme;
Now when you'll create a h2 component (<Heading as="h2">h2 text</Heading>), it will use this font.
You'll notice that unfortunately, I had to use 'font-family' instead of fontFamily (it seems to be an existing bug, same for font-weight).
To use different fonts in Buttons, you can customize Buttons components from your theme.
in const theme, the same way as fonts you need to create a components object:
const theme = extendTheme({
fonts: {
heading: "Open Sans", body: "Raleway",
},
components: {
Button: {
baseStyle: {
fontFamily: 'yourfont here'
}
}
}
})
You can do the same with other state of buttons for example _hover, _focus, _isDisabled, etc.

React load fonts dynamically from the backend

I want to be able to choose font I wish to download from backend via select and then use it in my project. User can change fonts and download new ones. I have problem that if font is fixed in my css like this:
export const MainContent = styled.div`
#font-face {
font-family: 'Lobster';
src: local('Font Name'), local('FontName'),
url ('http://localhost/font/lobster') format('woff');
font-weight: bold;
font-style: normal;
font-display: swap;
};
font-family: 'Lobster';
`;
It is downloaded properly right after app starts and I can use it, however I don't want to have it fixed, tried few solutions so far like with WebFont:
import WebFont from 'webfontloader';
function App() {
enter code here
WebFont.load({
custom: {
families: ['Lobster'],
urls: ['http://localhost/font/${fontname'] <= used fixed lobster in this case
}
});
...
}
But it throws error like =
The resource from “http://localhost/font/lobster” was blocked due to MIME type (“font/ttf”) mismatch (X-Content-Type-Options: nosniff).
another idea was to send parameter which could replace for example lobster via props of styled component like
<MainContent fontName="lobsterTheSecond">
...
</MainContent>
However I don't really know how to pass props in #font-face as it keeps throwing errors.
Does anyone knows how can I add fonts dynamically from backend while app works? I'm out of ideas already
Not sure about WebFont but it can be done quite easy with styled components:
First of all don't pass it to your 'MainContent' but rather pass props with new font to your globalStyles and then do something like that:
const GlobalStyle = createGlobalStyle`
body {
#font-face {
font-family: 'Lobster';
src: `${props =>
url ('http://localhost/font/${props.fontName}')` format('woff');
font-weight: bold;
font-style: normal;
font-display: swap;
};
}
`
and pass it like:
function App() {
const [newFont, setNewFont] = useState('');
return (
<div>
<GlobalStyle fontName{newFont} />
<button onClick={() => setNewFont('myNewFont')>Click</button>
</div>
)
}
and then in your MainContent just use this font:
const MainContent = styled.div`
font-family: 'Lobster';
`

Using Font awesome in Kendo grid

I use Font awesome in Kendo grid. I expect to work without problems , it shows as good as possible , Actually if I click on icon (each icon has parent) it will jump. Any idea about fixing this issue?
Here is my code:
<kendogrid
entity_id='restaurantId'
fields="{restaurantId: {editable: false, nullable: true},rgn: {required: true},type: {required: true},url: {editable: false, nullable: true}}"
controller="restaurant"
tools='false'
colmns='[
{
field: "restaurantId",
title: "id",
width: "100px",
locked: true,
lockable: true,
},
{
field: "type",
title:"type ",
width: "120px",
lockable: true,
minScreenWidth: 500,
sortable :false
},
{
field:"restaurantRateAverage" ,
title:"average ",
width: "80px",
lockable: true
},
{
title: "operation",
width: "110px",
lockable: true,
template: "
<a class=\"warning-color knd-custom-action-btn\" href=\"\\#/foods/add/${restaurantId}\" ><i class=\"fa fa-cutlery\"></i></a>
<a class=\"primary2-color knd-custom-action-btn\" href=\"\\#/delivery-zones/add/${restaurantId}/${restaurantCityId}\" ><i class=\"fa fa-map-marker\"></i></a>
<a class=\"danger-color knd-custom-action-btn k-grid-delete show-${restaurantId}\" href=\"\\#\"><span class=\"fa fa-times\"></span></a>
"
}
]'
hard-delete="true"
></kendogrid>
EDITED :
After reading this link I changed my code :
css :
#font-face {
font-family: "FontAwesome";
/*public/app/admin/assets/fonts/fontawesome-webfont.woff */
src: url("../fonts/fontawesome-webfont.woff") format("woff"),
url("../fonts/fontawesome-webfont.woff") format("truetype");
}
.km-icon:after,
.km-icon:before
{
font: 1em/1em "FontAwesome";
}
html:
{
field:"restaurantRateAverage" ,
title:"average ",
width: "80px",
lockable: true,
template: "<div data-role=\"tabstrip\">
<a data-icon=\"fa fa-check\"> </a></div>"
}
Actually it print fa fa-check and doesn't show fontawesome.
To display font-icons you need not only the font but also the correct CSS to display the correct icon. The "correct CSS" is not the same for everyone, since there are many ways to get the font.
You can get it from http://fontello.com and only select icons you really need (there are also some other services like fontello, I would advise to use on of them to only select the icons you really need)
After you get your font you have to implement it in your site. You already did this step, you declared a #font-face and used the font on your km-icon (font: 1em/1em "FontAwesome";)
Finally you need to say which icon to display for your km-icon, if you get the icons from fontello, you get a demo.html where all the unicode-codes for your CSS are stored, if you get it from the fontawesome site use this cheat sheet. You can either copy-paste the icon directly from there with the developer-tools, but since you don't have the font in your css-editor it will show up as . (or a ? or something similar, depending on what program you use)
Another way to specify it in the CSS is with the -notation, for example:
.icon-example::before{
content: '\e83e';
font-family: "Font Awesome";
}
The last way to add it is to do it like they did it on the fontawesome-site, to add the icon directly into the html, have a look at the font-awesome cheat-sheet site i linked earlier to see what I mean.

Resources