|
| 1 | +/** |
| 2 | + * Tag input library shared by the custom element and the standalone IIFE. |
| 3 | + * Initializes Tagify on Symfony form fields enhanced with data-nowo-tag-input attributes. |
| 4 | + */ |
| 5 | + |
| 6 | +import Tagify from '@yaireo/tagify'; |
| 7 | + |
| 8 | +import { createBundleLogger } from './logger'; |
| 9 | +import type { BundleLogger } from './logger'; |
| 10 | + |
| 11 | +export const TAG_NOWO_TAG_INPUT = 'nowo-tag-input'; |
| 12 | +export const HOST_SELECTOR = `${TAG_NOWO_TAG_INPUT}, [data-nowo-tag-container="1"]`; |
| 13 | +export const INPUT_SELECTOR = |
| 14 | + 'input[data-controller*="nowo-tag-input"], textarea[data-controller*="nowo-tag-input"]'; |
| 15 | + |
| 16 | +export type TagifyInput = HTMLInputElement | HTMLTextAreaElement; |
| 17 | + |
| 18 | +export type TagifySettings = { |
| 19 | + maxTags?: number; |
| 20 | + whitelist?: string[]; |
| 21 | + pattern?: RegExp | null; |
| 22 | + duplicates?: boolean; |
| 23 | + dropdown?: { |
| 24 | + enabled: boolean; |
| 25 | + maxItems: number; |
| 26 | + closeOnSelect: boolean; |
| 27 | + highlightFirst: boolean; |
| 28 | + }; |
| 29 | + placeholder?: string; |
| 30 | +}; |
| 31 | + |
| 32 | +let bundleLogger: BundleLogger | null = null; |
| 33 | + |
| 34 | +/** |
| 35 | + * @param logger - Bundle logger used by init helpers. |
| 36 | + */ |
| 37 | +export function setBundleLogger(logger: BundleLogger): void { |
| 38 | + bundleLogger = logger; |
| 39 | +} |
| 40 | + |
| 41 | +/** |
| 42 | + * @returns Active logger, or a silent fallback if the entry has not registered one. |
| 43 | + */ |
| 44 | +export function getLogger(): BundleLogger { |
| 45 | + if (bundleLogger !== null) { |
| 46 | + return bundleLogger; |
| 47 | + } |
| 48 | + |
| 49 | + return createBundleLogger('tag-input'); |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * @param value - Attribute/dataset flag. |
| 54 | + */ |
| 55 | +export function toBool(value: string | undefined): boolean { |
| 56 | + return value === '1' || value === 'true'; |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | + * @param raw - JSON array of allowed tags. |
| 61 | + */ |
| 62 | +export function parseWhitelist(raw: string | undefined): string[] | undefined { |
| 63 | + if (!raw) { |
| 64 | + return undefined; |
| 65 | + } |
| 66 | + |
| 67 | + try { |
| 68 | + const parsed = JSON.parse(raw) as unknown; |
| 69 | + if (!Array.isArray(parsed)) { |
| 70 | + return undefined; |
| 71 | + } |
| 72 | + |
| 73 | + return parsed.filter((item): item is string => typeof item === 'string'); |
| 74 | + } catch { |
| 75 | + getLogger().warn('invalid whitelist JSON', { raw }); |
| 76 | + return undefined; |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +/** |
| 81 | + * @param raw - Regex source without delimiters. |
| 82 | + */ |
| 83 | +export function parsePattern(raw: string | undefined): RegExp | null { |
| 84 | + if (!raw) { |
| 85 | + return null; |
| 86 | + } |
| 87 | + |
| 88 | + try { |
| 89 | + return new RegExp(raw); |
| 90 | + } catch { |
| 91 | + getLogger().warn('invalid pattern regex', { raw }); |
| 92 | + return null; |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +/** |
| 97 | + * @param input - Native field Tagify wraps. |
| 98 | + */ |
| 99 | +export function buildSettings(input: TagifyInput): TagifySettings { |
| 100 | + const dataset = input.dataset; |
| 101 | + const maxTagsRaw = dataset.nowoTagInputMaxTagsValue; |
| 102 | + const settings: TagifySettings = { |
| 103 | + duplicates: toBool(dataset.nowoTagInputDuplicatesValue), |
| 104 | + dropdown: { |
| 105 | + enabled: toBool(dataset.nowoTagInputDropdownEnabledValue), |
| 106 | + maxItems: 20, |
| 107 | + closeOnSelect: true, |
| 108 | + highlightFirst: true, |
| 109 | + }, |
| 110 | + }; |
| 111 | + |
| 112 | + if (maxTagsRaw !== undefined && maxTagsRaw !== '') { |
| 113 | + const maxTags = Number.parseInt(maxTagsRaw, 10); |
| 114 | + if (!Number.isNaN(maxTags) && maxTags > 0) { |
| 115 | + settings.maxTags = maxTags; |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + const whitelist = parseWhitelist(dataset.nowoTagInputWhitelistValue); |
| 120 | + if (whitelist !== undefined && whitelist.length > 0) { |
| 121 | + settings.whitelist = whitelist; |
| 122 | + } |
| 123 | + |
| 124 | + const pattern = parsePattern(dataset.nowoTagInputPatternValue); |
| 125 | + if (pattern !== null) { |
| 126 | + settings.pattern = pattern; |
| 127 | + } |
| 128 | + |
| 129 | + const placeholder = dataset.nowoTagInputPlaceholderValue; |
| 130 | + if (placeholder !== undefined && placeholder !== '') { |
| 131 | + settings.placeholder = placeholder; |
| 132 | + } |
| 133 | + |
| 134 | + return settings; |
| 135 | +} |
| 136 | + |
| 137 | +/** |
| 138 | + * @param input - Native field to enhance. |
| 139 | + */ |
| 140 | +export function initTagInput(input: TagifyInput): void { |
| 141 | + if (input.dataset.nowoTagInputInitialized === '1') { |
| 142 | + return; |
| 143 | + } |
| 144 | + |
| 145 | + const settings = buildSettings(input); |
| 146 | + // Tagify mutates the input in place; the instance is owned by the host element. |
| 147 | + new Tagify(input, settings); |
| 148 | + input.dataset.nowoTagInputInitialized = '1'; |
| 149 | +} |
| 150 | + |
| 151 | +/** |
| 152 | + * Initialize Tagify on a host custom element or legacy wrapper. |
| 153 | + * |
| 154 | + * @param host - `<nowo-tag-input>` or `[data-nowo-tag-container]`. |
| 155 | + */ |
| 156 | +export function initTagContainer(host: HTMLElement): void { |
| 157 | + const input = host.querySelector<TagifyInput>(INPUT_SELECTOR); |
| 158 | + if (input) { |
| 159 | + initTagInput(input); |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +/** |
| 164 | + * Discover and initialize every tag field currently in the document. |
| 165 | + */ |
| 166 | +export function initAllTagInputs(): void { |
| 167 | + const inputs = Array.from(document.querySelectorAll<TagifyInput>(INPUT_SELECTOR)); |
| 168 | + getLogger().info('initializing tag inputs', { count: inputs.length }); |
| 169 | + inputs.forEach(initTagInput); |
| 170 | +} |
| 171 | + |
| 172 | +let observer: MutationObserver | null = null; |
| 173 | + |
| 174 | +/** |
| 175 | + * Initialize existing hosts and watch for nodes added later (Turbo / live forms). |
| 176 | + */ |
| 177 | +export function runInitAndObserve(): void { |
| 178 | + initAllTagInputs(); |
| 179 | + if (observer !== null || typeof MutationObserver === 'undefined' || document.body === null) { |
| 180 | + return; |
| 181 | + } |
| 182 | + |
| 183 | + observer = new MutationObserver((mutations) => { |
| 184 | + for (const mutation of mutations) { |
| 185 | + mutation.addedNodes.forEach((node) => { |
| 186 | + if (!(node instanceof HTMLElement)) { |
| 187 | + return; |
| 188 | + } |
| 189 | + if (node.matches(HOST_SELECTOR)) { |
| 190 | + initTagContainer(node); |
| 191 | + } else if (node.matches(INPUT_SELECTOR)) { |
| 192 | + initTagInput(node as TagifyInput); |
| 193 | + } |
| 194 | + node.querySelectorAll<HTMLElement>(HOST_SELECTOR).forEach(initTagContainer); |
| 195 | + node.querySelectorAll<TagifyInput>(INPUT_SELECTOR).forEach(initTagInput); |
| 196 | + }); |
| 197 | + } |
| 198 | + }); |
| 199 | + observer.observe(document.body, { childList: true, subtree: true }); |
| 200 | +} |
| 201 | + |
| 202 | +/** |
| 203 | + * Disconnect the document observer. Used by tests when resetting modules. |
| 204 | + */ |
| 205 | +export function stopObserving(): void { |
| 206 | + observer?.disconnect(); |
| 207 | + observer = null; |
| 208 | +} |
0 commit comments