Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ids): prefix all ids and references with a unique string [KHCP-13216] #391

Merged
merged 21 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@
"@semantic-release/git": "^10.0.1",
"@types/jsdom": "^21.1.7",
"@types/node": "^20.15.0",
"@types/node-emoji": "^2.1.0",
adamdehaven marked this conversation as resolved.
Show resolved Hide resolved
"@vitejs/plugin-vue": "^5.1.2",
"@vitest/ui": "^2.0.5",
"@vue/test-utils": "^2.4.6",
Expand Down
12 changes: 0 additions & 12 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,7 @@ exports[`generate > does not remove icons from the previous build 1`] = `
"InsomniaIcon.vue",
"ItalicIcon.vue",
"KeyboardReturnIcon.vue",
"KongGradientIcon.vue",
Copy link
Member Author

@adamdehaven adamdehaven Sep 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’m not sure why this entry doesn’t already exist on main 🤔 but explains why the open Renovate PRs are failing.

"KongIcon.vue",
"LanguageBashIcon.vue",
"LanguageCIcon.vue",
Expand Down
78 changes: 77 additions & 1 deletion src/__template__/ComponentTemplate.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script lang="ts" setup>
/** {%%ICON_COMPONENT_FILE_HEADER%%} */
import { computed } from 'vue'
import { computed, ref, onMounted } from 'vue'
import { KUI_ICON_SIZE_50 } from '@kong/design-tokens'

const props = defineProps({
Expand Down Expand Up @@ -56,8 +56,19 @@ const props = defineProps({
required: false,
default: 'span',
},
/**
* A boolean to enable prefixing any internal SVG ids with a unique string; useful when there are potentially multiple SVG instances on the same page and the SVG utilizes ids and references internally (e.g. in the `<defs>` tag).
* Typically only set to false during snapshot testing.
* Defaults to `true`.
*/
randomizeIds: {
type: Boolean,
default: true,
},
adamdehaven marked this conversation as resolved.
Show resolved Hide resolved
})

const svgElement = ref<SVGElement | null>(null)

const iconSize = computed((): string => {
// If props.size is a number, ensure it's greater than zero
if (typeof props.size === 'number' && props.size > 0) {
Expand Down Expand Up @@ -90,6 +101,70 @@ const rootElementStyles = computed((): Record<string, string> => ({
lineHeight: '0',
width: iconSize.value,
}))

/**
* Prefix all ids within the SVG element and update all corresponding references to these ids. This is useful to avoid id conflicts when utilizing multiple instances of the same SVG in the DOM.
*
* @param {SVGElement} svgElement - The SVG element whose potential IDs need to be prefixed.
*/
const prefixSvgIds = (svgElement: SVGElement): void => {
if (!svgElement) {
return
}

const defsElement = svgElement.querySelector('defs')

// Prepare a map to store the original and new IDs for quick lookups
const idMap: Record<string, string> = {}

if (defsElement) {
// Prefix all direct children of <defs> that have an `id`
defsElement.querySelectorAll('[id]').forEach((element) => {
const originalId = element.getAttribute('id')
const newId = `${Math.random().toString(36).substring(2, 12)}-${originalId}`

// Map old id to new id
idMap[originalId!] = newId

// Update the element's id with the new prefixed id
element.setAttribute('id', newId)
})
}
adamdehaven marked this conversation as resolved.
Show resolved Hide resolved

// Update all references to these prefixed ids in attributes like `url(#id)`, `href`, `xlink:href`
const referencingAttributes = ['fill', 'stroke', 'filter', 'mask', 'clip-path', 'xlink:href', 'href']
adamdehaven marked this conversation as resolved.
Show resolved Hide resolved

// Function to update references to ids in attributes
const updateReferences = (element: Element): void => {
referencingAttributes.forEach((attr) => {
const attrValue = element.getAttribute(attr)
if (attrValue) {
// Match any url(#id) or href="#id" references
const updatedValue = attrValue.replace(/url\(#([^)]+)\)/g, (match, id) => {
adamdehaven marked this conversation as resolved.
Show resolved Hide resolved
return idMap[id] ? `url(#${idMap[id]})` : match
}).replace(/#([^\s]+)/g, (match, id) => {
return idMap[id] ? `#${idMap[id]}` : match
})

// If the value changed, update the attribute
if (updatedValue !== attrValue) {
element.setAttribute(attr, updatedValue)
}
}
})
}

// Traverse all elements in the SVG to update id references
svgElement.querySelectorAll('*').forEach((element) => {
updateReferences(element)
})
}

onMounted(() => {
if (props.randomizeIds && svgElement.value) {
prefixSvgIds(svgElement.value)
}
})
adamdehaven marked this conversation as resolved.
Show resolved Hide resolved
</script>

<template>
Expand All @@ -101,6 +176,7 @@ const rootElementStyles = computed((): Record<string, string> => ({
:style="rootElementStyles"
>
<svg
ref="svgElement"
:aria-hidden="decorative ? 'true' : undefined"
data-testid="kui-icon-svg-{%%KONG_COMPONENT_ICON_CLASS%%}"
fill="none"
Expand Down
3 changes: 3 additions & 0 deletions src/tests/generated-component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { KUI_COLOR_TEXT_PRIMARY } from '@kong/design-tokens'
for (const [componentName, IconComponent] of Object.entries(importedComponents)) {
describe(`${componentName}.vue`, () => {
it('has proper default structure', () => {
// @ts-ignore: dynamic component
const wrapper = mount(IconComponent)

expect(wrapper.exists()).toBe(true)
Expand All @@ -22,8 +23,10 @@ for (const [componentName, IconComponent] of Object.entries(importedComponents))
})

it('matches snapshot', () => {
// @ts-ignore: dynamic component interface
const wrapper = mount(IconComponent, {
props: {
randomizeIds: false, // Prevents random IDs from being generated for consistent snapshot testing
title: 'My custom title',
color: KUI_COLOR_TEXT_PRIMARY,
display: 'inline-flex',
Expand Down