@@ -177,3 +177,64 @@ function getAvailableTranslations(Page $page): array
177177 return $ availableTranslations ;
178178 }
179179}
180+
181+
182+ /**
183+ * Reads the SVG content and adds accessibility attributes based on custom fields.
184+ *
185+ * @param File $file The file object representing the SVG.
186+ * @param string $title The title for the SVG (optional).
187+ * @param string $description The description for the SVG (optional).
188+ * @param bool $isDecorative Whether the SVG is decorative (optional).
189+ * @return string The modified SVG content with accessibility attributes.
190+ */
191+ if (!function_exists ('readAccessible ' )) {
192+ function readAccessible (File $ file , string $ title = '' , string $ description = '' , bool $ isDecorative = false ): string
193+ {
194+ if ($ file ->extension () !== 'svg ' ) {
195+ return $ file ->read ();
196+ }
197+
198+ $ svgContent = $ file ->read ();
199+
200+ // Try to get values from custom fields if not provided
201+ if (empty ($ title ) && $ file ->svgTitle ()->isNotEmpty ()) {
202+ $ title = $ file ->svgTitle ()->value ();
203+ }
204+
205+ if (empty ($ description ) && $ file ->svgDescription ()->isNotEmpty ()) {
206+ $ description = $ file ->svgDescription ()->value ();
207+ }
208+
209+ // Check if marked as decorative in custom field
210+ if ($ file ->svgDecorative ()->toBool ()) {
211+ $ isDecorative = true ;
212+ }
213+
214+ if ($ isDecorative ) {
215+ $ svgContent = str_replace (
216+ '<svg ' ,
217+ '<svg aria-hidden="true" ' ,
218+ $ svgContent
219+ );
220+ } else {
221+ $ uniqueId = uniqid ('svg- ' );
222+ $ finalTitle = $ title ?: $ file ->alt ()->or ($ file ->name ())->value ();
223+
224+ // aria-labelledby="uniqueTitleID uniqueDescID" (use the title and desc ID’s) – both title and description are included in aria-labelledby because it has better screen-reader support than aria-describedby (see tip #4)
225+ $ ariaAttributes = 'role="img" aria-labelledby=" ' . $ uniqueId . '-title" ' ;
226+ if ($ description ) {
227+ $ ariaAttributes = 'role="img" aria-labelledby=" ' . $ uniqueId . '-title ' . $ uniqueId . '-desc" ' ;
228+ }
229+
230+ $ svgContent = str_replace ('<svg ' , '<svg ' . $ ariaAttributes , $ svgContent );
231+
232+ $ titleElement = '<title id=" ' . $ uniqueId . '-title"> ' . Html::encode ($ finalTitle ) . '</title> ' ;
233+ $ descElement = $ description ? '<desc id=" ' . $ uniqueId . '-desc"> ' . Html::encode ($ description ) . '</desc> ' : '' ;
234+
235+ $ svgContent = preg_replace ('/(<svg[^>]*>)/ ' , '$1 ' . $ titleElement . $ descElement , $ svgContent );
236+ }
237+
238+ return $ svgContent ;
239+ }
240+ }
0 commit comments