summaryrefslogtreecommitdiff
path: root/node_modules/postcss-fontpath/index.js
blob: 2fd38c5e8de0d3fcc93d226d2d9081af9cbd85a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'use strict';

var fs = require('fs'),
    path = require('path'),
    postcss = require('postcss'),
    url = require('url');

var DEFAULT_OPTS = {
  checkFiles: false,
  ie8Fix: false,
  formats: [
    { type: 'embedded-opentype', ext: 'eot' },
    { type: 'woff2', ext: 'woff2' },
    { type: 'woff', ext: 'woff' },
    { type: 'truetype', ext: 'ttf' },
    { type: 'svg', ext: 'svg'}
  ]
};

module.exports = postcss.plugin('postcss-fontpath', function(opts) {

  var config = Object.assign({}, DEFAULT_OPTS, opts || {});

  return function (css) {
    // Loop through each @rule
    css.walkAtRules('font-face', function(rule) {

      // Loop through each decleration in the rule
      rule.walkDecls('font-path', function(decl) {

        // Replace single and double quotes with nothing
        var fontPath = decl.value.replace(/"/g, '').replace(/'/g, ''),
          fonts = [],
          ieHack = false,
          ext = '';

        config.formats.forEach(function(format) {

          if (config.checkFiles) {
            // Best guess at where our fonts might be relative to
            var basePath = css.source.input.file || process.cwd(),
                absoluteFontPath = url.parse(path.resolve(path.dirname(basePath), fontPath) + '.' + format.ext).pathname;

            try {
              // Try to see if the font exists
              fs.accessSync(absoluteFontPath, fs.F_OK);
            } catch (err) {
              return;
            }
          }

          // Set the ext var
          ext = format.ext;

          if (ext === 'eot' && config.ie8Fix) {
            ieHack = true;
            ext = 'eot?#iefix';
          }

          // Add the font to the font-face decl
          fonts.push('url("' + fontPath + '.' + ext + '") format(\'' + format.type + '\')');
        });

        if (fonts.length > 0) {

          // If the EOT exists, add the fallback
          if (ieHack && config.ie8Fix) {
            decl.cloneBefore({
              prop: 'src',
              value: 'url("' + fontPath + '.eot")'
            });
          }

          // Implode the rest of the fonts
          decl.cloneBefore({
            prop: 'src',
            value: fonts.join(',\n       ')
          });
        }

        // Remove our custom decleration
        decl.remove();

      });

    });
  };
});