Skip to content

Commit 0e66943

Browse files
authored
Merge pull request #519 from BeAPI/ci/svg
Build icons as plain SVG
2 parents 8bcfc34 + 6b8b7f5 commit 0e66943

5 files changed

Lines changed: 258 additions & 20 deletions

File tree

‎config/plugins.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPl
1212
const WebpackImageSizesPlugin = require('./webpack-image-sizes-plugin')
1313
const WebpackThemeJsonPlugin = require('./webpack-theme-json-plugin')
1414
const SpriteHashPlugin = require('./webpack-sprite-hash-plugin')
15+
const WebpackIconFilesPlugin = require('./webpack-icon-files-plugin')
1516

1617
module.exports = {
1718
get: function (mode) {
@@ -20,6 +21,11 @@ module.exports = {
2021
watch: mode !== 'production',
2122
}),
2223
new SpriteHashPlugin(),
24+
new WebpackIconFilesPlugin({
25+
sourcePath: 'src/img/icons',
26+
outputPath: 'dist/images',
27+
silence: true,
28+
}),
2329
new CleanWebpackPlugin({
2430
cleanOnceBeforeBuildPatterns: ['**/*', '!images', '!images/**'],
2531
}),

‎config/svgo.config.js‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ module.exports = {
77
name: 'removeViewBox',
88
active: false,
99
},
10-
// Plugins that are not in the "preset-default" and that you want to activate
1110
'removeTitle',
1211
'convertStyleToAttrs',
1312
'prefixIds',
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
const fs = require('fs')
2+
const path = require('path')
3+
const { optimize } = require('svgo')
4+
const svgoConfig = require('./svgo.config')
5+
6+
/**
7+
* Webpack plugin that writes optimized standalone SVG files from icon sources.
8+
* Sprite sheets under dist/icons are unchanged; this mirrors src/img/icons/** into dist/images/**.
9+
*
10+
* @class WebpackIconFilesPlugin
11+
*/
12+
class WebpackIconFilesPlugin {
13+
/**
14+
* @param {Object} [options={}] Plugin options.
15+
* @param {string} [options.sourcePath='src/img/icons'] Source icons directory.
16+
* @param {string} [options.outputPath='dist/images'] Output directory (subfolders preserved).
17+
* @param {boolean} [options.silence=false] Suppress console output.
18+
*/
19+
constructor(options = {}) {
20+
this.options = {
21+
sourcePath: 'src/img/icons',
22+
outputPath: 'dist/images',
23+
silence: false,
24+
...options,
25+
}
26+
}
27+
28+
/**
29+
* @param {string} level Log level.
30+
* @param {...any} args Log arguments.
31+
*/
32+
log(level, ...args) {
33+
if (!this.options.silence) {
34+
console[level](...args)
35+
}
36+
}
37+
38+
/**
39+
* @param {string} directory Directory to scan.
40+
* @return {string[]} Absolute paths to SVG files.
41+
*/
42+
collectSvgFiles(directory) {
43+
const files = []
44+
45+
if (!fs.existsSync(directory)) {
46+
return files
47+
}
48+
49+
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
50+
const fullPath = path.join(directory, entry.name)
51+
52+
if (entry.isDirectory()) {
53+
files.push(...this.collectSvgFiles(fullPath))
54+
continue
55+
}
56+
57+
if (entry.name.endsWith('.svg')) {
58+
files.push(fullPath)
59+
}
60+
}
61+
62+
return files
63+
}
64+
65+
/**
66+
* @param {import('webpack').Compiler} compiler Webpack compiler.
67+
*/
68+
apply(compiler) {
69+
compiler.hooks.afterEmit.tapAsync('WebpackIconFilesPlugin', (compilation, callback) => {
70+
const context = compiler.options.context
71+
const sourceDir = path.resolve(context, this.options.sourcePath)
72+
const outputDir = path.resolve(context, this.options.outputPath)
73+
const svgFiles = this.collectSvgFiles(sourceDir)
74+
75+
if (svgFiles.length === 0) {
76+
callback()
77+
return
78+
}
79+
80+
let written = 0
81+
82+
for (const sourceFile of svgFiles) {
83+
const relativePath = path.relative(sourceDir, sourceFile)
84+
const destFile = path.join(outputDir, relativePath)
85+
86+
fs.mkdirSync(path.dirname(destFile), { recursive: true })
87+
88+
const input = fs.readFileSync(sourceFile, 'utf8')
89+
const result = optimize(input, {
90+
path: sourceFile,
91+
...svgoConfig,
92+
})
93+
94+
if (result.error) {
95+
console.warn(`WebpackIconFilesPlugin: SVGO failed for ${relativePath}: ${result.error}`)
96+
continue
97+
}
98+
99+
fs.writeFileSync(destFile, result.data)
100+
written++
101+
}
102+
103+
this.log('log', `WebpackIconFilesPlugin: Wrote ${written} optimized SVG(s) to ${this.options.outputPath}`)
104+
105+
callback()
106+
})
107+
}
108+
}
109+
110+
module.exports = WebpackIconFilesPlugin

‎inc/Helpers/Svg.php‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,30 @@
77
* @usage BEA\Theme\Framework\Helpers\Svg\get_the_icon( 'like' );
88
*
99
* @param string $icon_class
10-
* @param array $additionnal_classes
10+
* @param array $additionnal_classes
11+
* @param bool $is_sprite
1112
*
1213
* @return string
1314
*/
14-
function get_the_icon( string $icon_class, $additionnal_classes = [] ): string {
15+
function get_the_icon( string $icon_class, $additionnal_classes = [], bool $is_sprite = true ): string {
1516
/**
1617
* @var Svg $svg
1718
*/
1819
$svg = \BEA\Theme\Framework\Framework::get_container()->get_service( 'svg' );
19-
return false !== $svg ? $svg->get_the_icon( $icon_class, $additionnal_classes ) : '';
20+
return false !== $svg ? $svg->get_the_icon( $icon_class, $additionnal_classes, $is_sprite ) : '';
2021
}
2122

2223
/**
2324
* @usage BEA\Theme\Framework\Helpers\Svg\the_icon( 'like' );
2425
*
2526
* @param string $icon_class
2627
* @param array $additionnal_classes
28+
* @param bool $is_sprite
2729
*/
28-
function the_icon( string $icon_class, $additionnal_classes = [] ): void {
30+
function the_icon( string $icon_class, $additionnal_classes = [], bool $is_sprite = true ): void {
2931
/**
3032
* @var Svg $svg
3133
*/
3234
$svg = \BEA\Theme\Framework\Framework::get_container()->get_service( 'svg' );
33-
false !== $svg ? $svg->the_icon( $icon_class, $additionnal_classes ) : '';
35+
false !== $svg ? $svg->the_icon( $icon_class, $additionnal_classes, $is_sprite ) : '';
3436
}

‎inc/Services/Svg.php‎

Lines changed: 135 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -33,16 +33,55 @@ public function get_service_name(): string {
3333
}
3434

3535
/**
36-
* @param string $icon_class
37-
* @param array $additionnal_classes
36+
* @param string $icon_class Icon identifier (e.g. menu, social/facebook, social.svg#icon-facebook).
37+
* @param array $additionnal_classes Extra CSS classes.
38+
* @param bool $is_sprite When true, output a sprite reference; when false, inline the SVG file from dist/images.
3839
*
3940
* @return string
4041
*/
41-
public function get_the_icon( string $icon_class, array $additionnal_classes = [] ): string {
42+
public function get_the_icon( string $icon_class, array $additionnal_classes = [], bool $is_sprite = true ): string {
4243
if ( empty( $icon_class ) ) {
4344
return '';
4445
}
4546

47+
$parts = $this->parse_icon_identifier( $icon_class );
48+
$classes = array_map(
49+
'sanitize_html_class',
50+
array_merge( [ 'icon', $parts['icon_slug'] ], $additionnal_classes )
51+
);
52+
53+
if ( ! $is_sprite ) {
54+
return $this->get_inline_icon_markup( $parts['sprite_name'], $parts['file_base'], $classes );
55+
}
56+
57+
$icon_url = \get_theme_file_uri( sprintf( '/dist/icons/%s.svg', $parts['sprite_name'] ) );
58+
$hash_sprite = $this->get_sprite_hash( $parts['sprite_name'] );
59+
60+
return sprintf(
61+
'<svg class="%s" aria-hidden="true" focusable="false"><use href="%s#%s"></use></svg>',
62+
implode( ' ', $classes ),
63+
add_query_arg( [ 'v' => $hash_sprite ], $icon_url ),
64+
$parts['icon_slug']
65+
);
66+
}
67+
68+
/**
69+
* @param string $icon_class Icon identifier.
70+
* @param array $additionnal_classes Extra CSS classes.
71+
* @param bool $is_sprite When true, output a sprite reference; when false, inline the SVG file.
72+
*/
73+
public function the_icon( string $icon_class, array $additionnal_classes = [], bool $is_sprite = true ): void {
74+
echo $this->get_the_icon( $icon_class, $additionnal_classes, $is_sprite ); //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
75+
}
76+
77+
/**
78+
* Normalizes an icon identifier into sprite folder, symbol id and file basename.
79+
*
80+
* @param string $icon_class Raw icon identifier.
81+
*
82+
* @return array{sprite_name: string, icon_slug: string, file_base: string}
83+
*/
84+
private function parse_icon_identifier( string $icon_class ): array {
4685
// acf-svg-icon already return sprite-name.svg#icon-name, ex: social.svg#icon-facebook
4786
// format the string to obtain sprite-name/icon-name
4887
$icon_class = str_replace( '.svg#icon-', '/', $icon_class );
@@ -55,22 +94,104 @@ public function get_the_icon( string $icon_class, array $additionnal_classes = [
5594
$icon_class = substr( $icon_class, $slash_pos + 1 );
5695
}
5796

58-
$icon_slug = strpos( $icon_class, 'icon-' ) === 0 ? $icon_class : sprintf( 'icon-%s', $icon_class );
59-
$classes = [ 'icon', $icon_slug ];
60-
$classes = array_merge( $classes, $additionnal_classes );
61-
$classes = array_map( 'sanitize_html_class', $classes );
62-
$icon_url = \get_theme_file_uri( sprintf( '/dist/icons/%s.svg', $sprite_name ) );
63-
$hash_sprite = $this->get_sprite_hash( $sprite_name );
97+
$sprite_name = preg_replace( '/[^a-z0-9-]/', '', strtolower( (string) $sprite_name ) );
98+
if ( '' === $sprite_name ) {
99+
$sprite_name = 'sprite';
100+
}
101+
102+
$icon_slug = str_starts_with( $icon_class, 'icon-' ) ? $icon_class : sprintf( 'icon-%s', $icon_class );
103+
$file_base = preg_replace( '/^icon-/', '', $icon_slug );
104+
$file_base = preg_replace( '/[^a-z0-9-]/', '', strtolower( (string) $file_base ) );
105+
106+
return [
107+
'sprite_name' => $sprite_name,
108+
'icon_slug' => $icon_slug,
109+
'file_base' => $file_base,
110+
];
111+
}
112+
113+
/**
114+
* Loads an optimized SVG from dist/images and merges wrapper classes onto the root element.
115+
*
116+
* @param string $sprite_name Icon subdirectory (e.g. sprite, social).
117+
* @param string $file_base SVG filename without extension.
118+
* @param array $classes CSS classes for the root SVG element.
119+
*
120+
* @return string
121+
*/
122+
private function get_inline_icon_markup( string $sprite_name, string $file_base, array $classes ): string {
123+
if ( '' === $file_base ) {
124+
return '';
125+
}
126+
127+
$relative_path = sprintf( 'dist/images/%s/%s.svg', $sprite_name, $file_base );
128+
$file_path = \get_theme_file_path( $relative_path );
129+
130+
if ( ! is_readable( $file_path ) ) {
131+
return '';
132+
}
133+
134+
$real_file = realpath( $file_path );
135+
$real_base = realpath( \get_theme_file_path( 'dist/images' ) );
136+
137+
if ( false === $real_file || false === $real_base || ! str_starts_with( $real_file, $real_base ) ) {
138+
return '';
139+
}
140+
141+
$svg_markup = file_get_contents( $real_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
64142

65-
return sprintf( '<svg class="%s" aria-hidden="true" focusable="false"><use href="%s#%s"></use></svg>', implode( ' ', $classes ), add_query_arg( [ 'v' => $hash_sprite ], $icon_url ), $icon_slug );
143+
if ( false === $svg_markup || '' === $svg_markup ) {
144+
return '';
145+
}
146+
147+
return $this->inject_svg_classes( $svg_markup, $classes );
66148
}
67149

68150
/**
69-
* @param string $icon_class
70-
* @param array $additionnal_classes
151+
* Merges classes and a11y attributes on the first root SVG element.
152+
*
153+
* @param string $svg_markup SVG file contents.
154+
* @param array $classes CSS classes to apply.
155+
*
156+
* @return string
71157
*/
72-
public function the_icon( string $icon_class, array $additionnal_classes = [] ): void {
73-
echo $this->get_the_icon( $icon_class, $additionnal_classes ); //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
158+
private function inject_svg_classes( string $svg_markup, array $classes ): string {
159+
$class_attr = implode( ' ', array_filter( $classes ) );
160+
161+
$updated = preg_replace_callback(
162+
'/<svg\b([^>]*)>/i',
163+
static function ( array $matches ) use ( $class_attr ): string {
164+
$attrs = $matches[1];
165+
166+
if ( '' !== $class_attr ) {
167+
if ( preg_match( '/\bclass=(["\'])([^"\']*)\1/i', $attrs, $class_match ) ) {
168+
$new_class = trim( $class_match[2] . ' ' . $class_attr );
169+
$attrs = preg_replace(
170+
'/\bclass=(["\'])([^"\']*)\1/i',
171+
'class="' . esc_attr( $new_class ) . '"',
172+
$attrs,
173+
1
174+
);
175+
} else {
176+
$attrs .= sprintf( ' class="%s"', esc_attr( $class_attr ) );
177+
}
178+
}
179+
180+
if ( ! preg_match( '/\baria-hidden=/i', $attrs ) ) {
181+
$attrs .= ' aria-hidden="true"';
182+
}
183+
184+
if ( ! preg_match( '/\bfocusable=/i', $attrs ) ) {
185+
$attrs .= ' focusable="false"';
186+
}
187+
188+
return '<svg' . $attrs . '>';
189+
},
190+
$svg_markup,
191+
1
192+
);
193+
194+
return is_string( $updated ) ? $updated : $svg_markup;
74195
}
75196

76197
/**

0 commit comments

Comments
 (0)