|
| 1 | +--- |
| 2 | +interface Props { |
| 3 | + name: string; |
| 4 | + placeholder?: string; |
| 5 | + wrapper?: boolean; |
| 6 | +} |
| 7 | +
|
| 8 | +const { |
| 9 | + name, |
| 10 | + placeholder = '', |
| 11 | + wrapper = false, |
| 12 | +} = Astro.props; |
| 13 | +--- |
| 14 | + |
| 15 | +<query-parameter data-name={name} data-wrapper={wrapper} data-placeholder={placeholder}> |
| 16 | + <slot /> |
| 17 | +</query-parameter> |
| 18 | + |
| 19 | +<script> |
| 20 | + // Source: https://stackoverflow.com/a/74362432 |
| 21 | + function sanitize(input: string) { |
| 22 | + const mapping: Record<string, string> = { |
| 23 | + '&': '&', |
| 24 | + '<': '<', |
| 25 | + '>': '>', |
| 26 | + '"': '"', |
| 27 | + "'": ''', |
| 28 | + '/': '/', |
| 29 | + }; |
| 30 | + |
| 31 | + const regularExpression = /[&<>"'/]/gi; |
| 32 | + return input.replace(regularExpression, match => mapping[match]); |
| 33 | + } |
| 34 | + |
| 35 | + class QueryParameter extends HTMLElement { |
| 36 | + constructor() { |
| 37 | + super(); |
| 38 | + |
| 39 | + // Wrap this element with a div element, because this custom element can break the layout around it. |
| 40 | + if (this.dataset.wrapper === 'true') { |
| 41 | + const newParent = document.createElement('div'); |
| 42 | + this.parentNode?.replaceChild(newParent, this); |
| 43 | + newParent.appendChild(this); |
| 44 | + } |
| 45 | + |
| 46 | + // Remove any whitespace text node right after this element, because we might have one before the injected script node, |
| 47 | + // and it adds a whitespace character which we don't want. |
| 48 | + if (this.nextSibling?.nodeType === Node.TEXT_NODE && this.nextSibling.textContent?.trim() === '') { |
| 49 | + this.nextSibling.remove(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + _replaceText(text: string, escapeText: boolean) { |
| 54 | + text = text.replaceAll('\\', '/'); |
| 55 | + |
| 56 | + if (this.dataset.wrapper === 'true') { |
| 57 | + const link = this.querySelector('a[href*="%s"]'); |
| 58 | + |
| 59 | + if (link instanceof HTMLAnchorElement) { |
| 60 | + link.href = link.href.replace('%s', text); |
| 61 | + } |
| 62 | + } else { |
| 63 | + this.innerHTML = escapeText ? sanitize(text) : text; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + connectedCallback() { |
| 68 | + if (this.dataset.name) { |
| 69 | + const urlParams = new URLSearchParams(window.location.search); |
| 70 | + |
| 71 | + if (urlParams.has(this.dataset.name)) { |
| 72 | + const value = urlParams.get(this.dataset.name)!.trim(); |
| 73 | + this._replaceText(value, true); |
| 74 | + return; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + if (this.dataset.placeholder) { |
| 79 | + this._replaceText(this.dataset.placeholder, false); |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + customElements.define('query-parameter', QueryParameter); |
| 85 | +</script> |
0 commit comments