<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mitya Novosad on Medium]]></title>
        <description><![CDATA[Stories by Mitya Novosad on Medium]]></description>
        <link>https://medium.com/@mityanovosad?source=rss-414f39b2eab6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bZD1ghyl8418LxjDovZZpw.png</url>
            <title>Stories by Mitya Novosad on Medium</title>
            <link>https://medium.com/@mityanovosad?source=rss-414f39b2eab6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:42:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mityanovosad/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[FontFace API: Handling the custom fonts with JavaScript]]></title>
            <link>https://medium.com/@mityanovosad/fontface-api-handling-the-custom-fonts-with-javascript-1c46fcfffda2?source=rss-414f39b2eab6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c46fcfffda2</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[fonts]]></category>
            <dc:creator><![CDATA[Mitya Novosad]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 15:39:52 GMT</pubDate>
            <atom:updated>2023-02-05T22:16:57.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gOXSA4ttkUfwSItn" /><figcaption>Photo by <a href="https://unsplash.com/@amadorloureiro?utm_source=medium&amp;utm_medium=referral">Amador Loureiro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s say we have a task to create a logo builder. It should allow users to choose a layout, pick colors, vector icons, and a shiny font from the list or even upload a custom font for themselves.<br>While most of this sounds like a day-to-day front-end developer job, working with custom fonts might be unusual. Surprisingly, there are very few solutions on the web helping to handle the fonts. And most of the existing solutions are focused on specific cases, i.e. Google Fonts. But what if our goal is to display a list of custom fonts in the assets folder or the CDN link? Most likely, the logo builder may use some fancy font and, as mentioned, allow users to upload the custom one, which they might have built with the designer for their brand.</p><p>This might look easy at first glance, but it can quickly get out of hand.<br>Let’s try to implement a little example for a font picker with a list of custom fonts. We will use React for this example, but the main idea is library agnostic and can be adjusted to any other JS framework. You can see the final result in the gif below. And check it out on the <a href="https://xmityaz.github.io/md-react-custom-font-picker/">example page</a> as well.</p><figure><img alt="Font picker example" src="https://cdn-images-1.medium.com/max/1024/1*Q-Is0QgJCr5V1Lehk-pgEg.gif" /><figcaption>Custom font picker example</figcaption></figure><h3>Loading the font</h3><p>Let’s start with the most basic task. How should the font be loaded? The most common way to do that is to include the @font-face at-rule in CSS. But it won’t scale too well. This approach definitely will work for a few fonts, but what if our list is quite big?</p><p>Moreover, when a font is included with a@font-face rule, the browser will start downloading it lazily as soon it is referenced by font-family property. This might not be the desired behavior if we want to show all the font options at once at some point. And there is no way of knowing that the requested font is already available. There is an option<strong> </strong>to use font-display CSS property to adjust UX slightly, but it won’t be ideal.</p><p>Some of those issues are possible to resolve by preloading each font beforehand in HTML. Howewer<strong>,</strong> this approach does not scale too well.</p><pre>&lt;link rel=&quot;preload&quot; href=&quot;path/to/font.woff2&quot; as=&quot;font&quot; type=&quot;font/woff2&quot; /&gt;</pre><p>So the idea is simple — we want to load the font dynamically and know when it will become available to display.</p><p>The browser FontFace API and document.fontscomes very useful here and helps to solve those issues.<br>Let’s see a simple example of defining and loading a custom font using the browserFontFaceAPI:</p><pre>cosnt font = new FontFace(&#39;Roman Capital&#39;, &#39;url(http://href-with-roman-capital.ttf/)&#39;);<br>font.load();</pre><p>font.load() will return a Promise. As soon as that promise resolves, we can use the font. Let’s see what it looks like with the concrete example:</p><pre>cosnt myFont = new FontFace(&#39;Roman Capital&#39;, &#39;url(http://href-with-roman-capital.ttf/)&#39;);<br>try {<br>  await myFont.load();<br>  document.fonts.add(newFont);<br>    <br>  // Now we can use our freshly loaded font<br>  document.body.style.fontFamily = &#39;Roman Capital&#39;;<br>} catch (e) {<br>  console.error(&#39;Roman Capital failed to load&#39;);<br>}</pre><p>When the “Roman Capital” font loaded, it was set as font family to the body element.</p><p>We can write a simple function now to load a font with an additional check in case the requested font was already uploaded.</p><pre>type Font = {name: string; src: string};<br><br>async function loadFont({name, src}: Font) {<br>  const fontAlreadyLoaded = document.fonts.check(`10px ${name}`);<br><br>  if (!fontAlreadyLoaded) {<br>    const fontFace = new FontFace(name, `url(https://medium.com/$%7Bsrc%7D)`);<br><br>    try {<br>      await fontFace.load();<br>      document.fonts.add(fontFace);<br>    } catch (e) {<br>      console.error(`Font ${name} failed to load`);<br>    }<br>  }<br>}</pre><p>This gives us a way to load the custom font and have a good idea of when it will be available.</p><h3>Creating a picker for the fonts</h3><p>Now we can use loadFont function to display a select component with all the options for fonts. Ideally, every option should be displayed with the font face it represents. The default browser &lt;select&gt; UI depends on the OS and does not provide much room for adjusting. So it has to be a custom component.</p><p>We will use <a href="https://react-select.com/">react-select</a> for this example. But it also can be a component of any DSL. Most such component libraries provide the ability to override the option element styles.</p><p>The basic implementation of our select component would look like this:</p><pre>function FontPicker({options, ...props}) {<br>  const fontOptions = useMemo(<br>    () =&gt; props.fonts.map((font) =&gt; {value: font.name, label: font.name}),<br>    [props.fonts]<br>  );<br>  const uploadFonts = () =&gt; {     <br>    props.options.forEach(font =&gt; loadFont(font.name, font.href));<br>  }<br><br>  return (<br>    &lt;Select<br>      options={fontOptions}<br>      onFocus={uploadFonts}<br>      styles={getCustomStyle()}<br>    /&gt;<br>  );<br>}</pre><p>But with that implementation, when a user opens the select menu for the first time, the items will show in the default parent font family and then will change to their appropriate font as soon as it is loaded by the browser, separately for each option.</p><p>To avoid such behavior, we would want to open the select menu only when all the fonts are up and ready. Let’s try to adopt our solution for this using react state:</p><pre>export function FontPicker({options, ...props}: FontPickerProps) {<br>  const [isFontsLoading, setIsFontsLoading] = useState(false);<br>  const [isFontsReady, setIsFontsReady] = useState(false);<br><br>  const fontOptions = useMemo(<br>    () =&gt; options.map((font) =&gt; ({label: font.name, value: font.name})),<br>    [options]<br>  );<br>  const uploadFonts = async () =&gt; {<br>    if (!isFontsReady &amp;&amp; !isFontsLoading) {<br>      setIsFontsLoading(true);<br><br>      const loadAllFonts = options.map((font) =&gt; loadFont(font));<br>      await Promise.all(loadAllFonts);<br>    }<br><br>    setIsFontsLoading(false);<br>    setIsFontsReady(true);<br>  };<br><br>  return (<br>    &lt;Select<br>      options={isFontsReady ? fontOptions : undefined}<br>      isLoading={isFontsLoading}<br>      onFocus={uploadFonts}<br>      styles={getCustomStyle()}<br>    /&gt;<br>  );<br>}</pre><p>I have moved the styles property to the separate getter for simplicity. It exists to set the font family for every single option and the input element after a user has picked a font. Here is how getCustomStyle() looks for react-select example:</p><pre>const getCustomStyle = () =&gt; ({<br>  // Set font-family for option<br>  option: (style, {data}) =&gt; ({<br>    ...style,<br>    fontFamily: data.value,<br>  }),<br><br>  // Set font-family for control input when an option selected<br>  control: (style, controlProps) =&gt; ({<br>    ...style,<br>    fontFamily: controlProps.getValue()?.[0]?.value,<br>  }),<br>})</pre><h3>Letting users upload their own font</h3><p>Now that we have a way to display the list of our custom fonts, let’s think about how to let users pick fonts of their own.</p><p>Obviously, it should start with the file upload input. It can be a simple file-upload input or a pretty drag’n’drop area. We won’t concentrate on styling for the file input too much.<br>What interests us, though, is how to use the uploaded font file and immediately apply it to the text in the browser. For that, we can slightly modify the implementation of our loadFont function:</p><pre>export type Font = {<br>  name: string;<br>  src: string | File; // (1)<br>};<br><br>export async function loadFont({name, src}: Font) {<br>  const fontAlreadyLoaded = document.fonts.check(`10px ${name}`);<br><br>  if (!fontAlreadyLoaded) {<br>    const fontFace = new FontFace(<br>      name,<br>      typeof src === &#39;string&#39; ? `url(https://medium.com/$%7Bsrc%7D)` : await src.arrayBuffer() // (2)<br>    );<br><br>    try {<br>      await fontFace.load();<br>      document.fonts.add(fontFace);<br>    } catch (e) {<br>      console.error(`Font ${name} failed to load`);<br>    }<br>  }<br>}</pre><p>This implementation is pretty identical to what it was before, with one important exception — it can accept File as a src property <strong>(1)</strong> and load it to the FontFace <strong>(2)</strong>.<br>Again, it gives us absolute control of whether the file loaded and if it is ready to be applied to the text.</p><p>So let’s now make a simple implementation for the file upload input that would be integrated with our loadFont function:</p><pre>type FontUploaderProps = {<br>  onFontUploaded?: (font?: string) =&gt; void;<br>};<br><br>export function FontUploader(props: FontUploaderProps) {<br>  const [isFontsLoading, setIsFontsLoading] = useState(false);<br><br>  const onFileUpload = async (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    const file = e?.target?.files?.[0];<br><br>    if (file) {<br>      setIsFontsLoading(true);<br><br>      const fontName = file?.name?.replace(/\.[^/.]+$/, &#39;&#39;) || &#39;custom font&#39;;<br>      await loadFont({name: fontName, src: file});<br><br>      setIsFontsLoading(false);<br>      props.onFontUploaded?.(fontName);<br>    }<br>  };<br><br>  return isFontsLoading ? (<br>    &lt;div&gt;Loading...&lt;/div&gt;<br>  ) : (<br>    &lt;input<br>      type=&quot;file&quot;<br>      accept=&quot;.ttf,.otf,.woff,woff2&quot;<br>      onChange={onFileUpload}<br>    /&gt;<br>  );<br>}</pre><p>That’s it. Now we can integrate those components into some wrapper component that would handle the state and update the fontFace in the text accordingly.</p><pre>function App() {<br>  const [font, setFont] = useState&lt;string&gt;();<br><br>  return (<br>    &lt;div className=&quot;App&quot; style={{fontFamily: font}}&gt;<br>      &lt;h1 style={{fontFamily: font}}&gt;<br>        The quick brown fox jumps over the lazy dog<br>      &lt;/h1&gt;<br><br>      &lt;FontPicker<br>        options={DEFAULT_FONT_LIST}<br>        value={font}<br>        onChange={(e) =&gt; setFont(e?.value)}<br>      /&gt;<br><br>      &lt;FontUploader<br>        onFontUploaded={(font?: string) =&gt; font &amp;&amp; setFont(font)}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Browser support</h3><p>How about browser support? FontFace API browser support is 94% and can be safely used unless IE support is required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VaDqmSW1yBok87HfRzcelw.png" /></figure><p>As a fallback for IE, it is possible to define every font with the CSS @font-face at-rule. And then, add it to your bundle or use bundler lazy-load capabilities to load the CSS on demand.<br>Such an approach will lack control over whether the font is ready to be displayed. But that is what you get when you choose to look at the web through the IE browser.</p><h3>Conclusion</h3><p>Usually, we don’t pay too much attention to how and when our fonts are loading onto the website. CSS font-face referencing the CDN link or the local file, bundled by webpack or a similar tool, does the work for us in most cases. But when we need to do something extraordinary with fonts, it might be an unusual and hard topic to dig through with little information on the web and few open-source tools. Luckily browsers have great built-in support for fonts manipulation using FontFace API that allows us to control everything related to the fonts on the web page. Starting from simple checks if the font is available to display, loading the fonts dynamically, and even allowing users to load their own font face to the page.</p><h3>Links</h3><ol><li>Example showcase page: <a href="https://xmityaz.github.io/md-react-custom-font-picker/">https://xmityaz.github.io/md-react-custom-font-picker/</a></li><li>Example GitHub repo: <a href="https://github.com/xmityaz/md-react-custom-font-picker">https://github.com/xmityaz/md-react-custom-font-picker</a></li><li>FontFace API: <a href="https://developer.mozilla.org/en-US/docs/Web/API/FontFace">https://developer.mozilla.org/en-US/docs/Web/API/FontFace</a></li><li>React Select: <a href="https://react-select.com/">https://react-select.com/</a></li><li>Thanks to fontspace for all the beautiful fonts: <a href="https://www.fontspace.com/">https://www.fontspace.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c46fcfffda2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>