stevage / map-gl-utils

A utility library that makes Mapbox GL JS or Maplibre GL a bit more convenient to work with.
https://npmjs.com/package/map-gl-utils
212 stars 24 forks source link

Add fontsInUse() #26

Closed stevage closed 3 years ago

stevage commented 3 years ago

A function to get a list of all the fonts used in the current style would be helpful. This function does most of it, although it won't find font names referred to in a ['format', ... { 'text-font': ... }] block.

function getFonts(map)
            function findLiterals(expr) {
                if (Array.isArray(expr)) {
                    if (expr[0] === 'literal') {
                        ///
                        fonts.push(...expr[1]);
                    } else {
                        expr.forEach(findLiterals);
                    }
                }
            }
            let fonts = [];
            const fontExprs = map
                .getStyle()
                .layers.map((l) => l.layout && l.layout['text-font'])
                .filter(Boolean);
            for (const fontExpr of fontExprs) {
                // if top level expression is an array of strings, it's hopefully ['Arial', ...] and not ['get', 'font']
                if (fontExpr.every((f) => typeof f === 'string')) {
                    fonts.push(...fontExpr);
                } else {
                    findLiterals(fontExpr);
                }
            }
            return [...new Set(fonts)];
}
stevage commented 3 years ago

Maybe .usedFonts()

stevage commented 3 years ago

Or .fontsInUse()