@kit-data-manager/pid-component
Version:
The PID-Component is a web component that can be used to evaluate and display FAIR Digital Objects, PIDs, ORCiDs, and possibly other identifiers in a user-friendly way. It is easily extensible to support other identifier types.
517 lines (510 loc) • 18.4 kB
JavaScript
/*!
*
* Copyright 2024-2026 Karlsruhe Institute of Technology.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
;
var PID = require('./PID-CeI07E24.js');
require('./index-SLWnk0w6.js');
require('./json-viewer.entry.cjs.js');
const SKIP_ELEMENTS = new Set([
'SCRIPT',
'STYLE',
'TEXTAREA',
'INPUT',
'SELECT',
'NOSCRIPT',
'PID-COMPONENT',
'CODE',
'PRE',
'SVG',
]);
const PROCESSED_ATTR = 'data-pid-auto-detected';
function shouldSkipElement(element, excludeSelector) {
if (SKIP_ELEMENTS.has(element.tagName)) {
return true;
}
if (element.hasAttribute('contenteditable')) {
return true;
}
if (element.hasAttribute(PROCESSED_ATTR)) {
return true;
}
if (element.closest('.pid-auto-detect-wrapper')) {
return true;
}
if (excludeSelector) {
try {
if (element.matches(excludeSelector)) {
return true;
}
}
catch (_a) {
}
}
return false;
}
function scanDom(root, excludeSelector, batchSize = 50) {
return new Promise((resolve) => {
const results = [];
let nextId = 0;
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, {
acceptNode(node) {
var _a;
if (node.nodeType === Node.ELEMENT_NODE) {
const element = node;
if (shouldSkipElement(element, excludeSelector)) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_SKIP;
}
const text = (_a = node.textContent) === null || _a === void 0 ? void 0 : _a.trim();
if (!text || text.length < 2) {
return NodeFilter.FILTER_SKIP;
}
return NodeFilter.FILTER_ACCEPT;
},
});
const requestIdle = typeof requestIdleCallback !== 'undefined'
? requestIdleCallback
: (cb) => setTimeout(() => cb({ timeRemaining: () => 16 }), 0);
function processNextBatch(deadline) {
let count = 0;
while (count < batchSize && deadline.timeRemaining() > 0) {
const node = walker.nextNode();
if (node === null) {
resolve(results);
return;
}
if (node.nodeType === Node.TEXT_NODE) {
const textNode = node;
const text = textNode.textContent || '';
if (text.trim().length >= 2) {
results.push({
id: nextId++,
textNode,
text,
});
}
count++;
}
}
requestIdle(processNextBatch);
}
requestIdle(processNextBatch);
});
}
const WRAPPER_CLASS = 'pid-auto-detect-wrapper';
const WRAPPER_ATTR = 'data-pid-auto-detected';
function replaceMatches(textNode, matches, config) {
var _a;
const records = [];
const parent = textNode.parentNode;
if (!parent)
return records;
const fullText = textNode.textContent || '';
const sortedMatches = [...matches]
.sort((a, b) => a.start - b.start)
.filter((match, i, arr) => i === 0 || match.start >= arr[i - 1].end);
const fragment = document.createDocumentFragment();
let lastIndex = 0;
for (const match of sortedMatches) {
if (match.start > lastIndex) {
fragment.appendChild(document.createTextNode(fullText.substring(lastIndex, match.start)));
}
const wrapper = document.createElement('span');
wrapper.className = WRAPPER_CLASS;
wrapper.setAttribute(WRAPPER_ATTR, 'true');
wrapper.style.display = 'inline';
const originalSpan = document.createElement('span');
originalSpan.textContent = match.value;
wrapper.appendChild(originalSpan);
const pidComponent = document.createElement('pid-component');
pidComponent.setAttribute('value', match.value);
if (config.renderers && config.renderers.length > 0) {
pidComponent.setAttribute('renderers', JSON.stringify(config.renderers));
}
pidComponent.setAttribute('fallback-to-all', String((_a = config.fallbackToAll) !== null && _a !== void 0 ? _a : true));
pidComponent.style.cssText = 'visibility:hidden;position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;';
pidComponent.setAttribute('aria-hidden', 'true');
applyConfig(pidComponent, config);
wrapper.appendChild(pidComponent);
const observer = createSwapObserver(originalSpan, pidComponent, wrapper);
fragment.appendChild(wrapper);
records.push({
wrapper,
originalText: match.value,
precedingTextNode: null,
followingTextNode: null,
pidComponent,
observer,
originalSpan,
});
lastIndex = match.end;
}
if (lastIndex < fullText.length) {
fragment.appendChild(document.createTextNode(fullText.substring(lastIndex)));
}
parent.replaceChild(fragment, textNode);
return records;
}
function applyConfig(pidComponent, config) {
var _a;
if (config.settings) {
const settingsStr = typeof config.settings === 'string'
? config.settings
: JSON.stringify(config.settings);
pidComponent.setAttribute('settings', settingsStr);
}
if (config.darkMode) {
pidComponent.setAttribute('dark-mode', config.darkMode);
}
if (config.levelOfSubcomponents !== undefined) {
pidComponent.setAttribute('level-of-subcomponents', String(config.levelOfSubcomponents));
}
if (config.itemsPerPage !== undefined) {
pidComponent.setAttribute('items-per-page', String(config.itemsPerPage));
}
pidComponent.setAttribute('emphasize-component', String((_a = config.emphasizeComponent) !== null && _a !== void 0 ? _a : false));
if (config.showTopLevelCopy !== undefined) {
pidComponent.setAttribute('show-top-level-copy', String(config.showTopLevelCopy));
}
if (config.defaultTTL !== undefined) {
pidComponent.setAttribute('default-t-t-l', String(config.defaultTTL));
}
}
function createSwapObserver(originalSpan, pidComponent, wrapper) {
let swapped = false;
let pollTimer = null;
let safetyTimer = null;
function cleanup() {
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
if (safetyTimer) {
clearTimeout(safetyTimer);
safetyTimer = null;
}
observer.disconnect();
}
function handleError() {
swapped = true;
cleanup();
pidComponent.remove();
unwrapToText(wrapper, originalSpan.textContent || '');
}
function handleSuccess() {
swapped = true;
cleanup();
originalSpan.style.display = 'none';
originalSpan.setAttribute('aria-hidden', 'true');
pidComponent.style.cssText = '';
pidComponent.removeAttribute('aria-hidden');
}
function trySwap() {
if (swapped)
return;
const shadowRoot = pidComponent.shadowRoot;
if (!shadowRoot)
return;
const allElements = shadowRoot.querySelectorAll('*');
if (allElements.length === 0)
return;
const hostInShadow = shadowRoot.querySelector('[class*="relative"]');
if (hostInShadow) {
const hostStyle = hostInShadow.style;
if (hostStyle && hostStyle.display === 'none') {
handleError();
return;
}
}
const errorEl = shadowRoot.querySelector('[role="alert"]');
if (errorEl) {
handleError();
return;
}
const spinner = shadowRoot.querySelector('.animate-spin');
if (spinner)
return;
const preview = shadowRoot.querySelector('[role="button"], pid-collapsible, a[href], copy-button, color-highlight, locale-visualization');
if (preview) {
handleSuccess();
return;
}
if (allElements.length > 2 && !spinner && !errorEl) {
handleSuccess();
return;
}
}
const observer = new MutationObserver(trySwap);
pollTimer = setInterval(() => {
if (swapped) {
cleanup();
return;
}
if (pidComponent.shadowRoot) {
try {
observer.observe(pidComponent.shadowRoot, {
childList: true,
subtree: true,
attributes: true,
});
}
catch (_a) {
}
trySwap();
}
}, 100);
safetyTimer = setTimeout(() => {
if (!swapped) {
trySwap();
if (!swapped) {
handleError();
}
}
}, 15000);
observer.observe(pidComponent, {
attributes: true,
childList: true,
});
return observer;
}
function unwrapToText(wrapper, text) {
const parent = wrapper.parentNode;
if (!parent)
return;
const textNode = document.createTextNode(text);
parent.replaceChild(textNode, wrapper);
parent.normalize();
}
function restoreOriginalText(records) {
for (const record of records) {
record.observer.disconnect();
unwrapToText(record.wrapper, record.originalText);
}
}
function buildDetectionRegistry() {
const priorities = new Map();
return PID.renderers
.filter(r => r.key !== 'FallbackType')
.map(renderer => {
var _a;
priorities.set(renderer.key, (_a = renderer.priority) !== null && _a !== void 0 ? _a : 99);
return {
key: renderer.key,
autoDiscoverableByDefault: renderer.autoDiscoverableByDefault,
check: (value) => {
const instance = new renderer.constructor(value);
return instance.quickCheck();
},
};
})
.sort((a, b) => { var _a, _b; return ((_a = priorities.get(a.key)) !== null && _a !== void 0 ? _a : 99) - ((_b = priorities.get(b.key)) !== null && _b !== void 0 ? _b : 99); });
}
let _detectionRegistry;
function getDetectionRegistry() {
if (!_detectionRegistry) {
_detectionRegistry = buildDetectionRegistry();
}
return _detectionRegistry;
}
const detectionRegistry = [];
getDetectionRegistry().forEach(entry => detectionRegistry.push(entry));
const LEADING_STRIP = /^[\s.,;:!?\-–—"'`´«»()[\]{}<>*/\\#@^~|]+/;
const TRAILING_STRIP = /[\s.,;:!?\-–—"'`´«»()[\]{}<>*/\\#@^~|]+$/;
function sanitizeToken(token) {
const leadingMatch = LEADING_STRIP.exec(token);
const leadingStripped = leadingMatch ? leadingMatch[0].length : 0;
let sanitized = token.substring(leadingStripped);
const trailingMatch = TRAILING_STRIP.exec(sanitized);
if (trailingMatch) {
sanitized = sanitized.substring(0, sanitized.length - trailingMatch[0].length);
}
return { sanitized, leadingStripped };
}
function detectBestFit(value, orderedRendererKeys, fallbackToAll = true) {
const registry = getDetectionRegistry();
if (orderedRendererKeys && orderedRendererKeys.length > 0) {
for (const key of orderedRendererKeys) {
const entry = registry.find(e => e.key === key);
if (entry && entry.check(value)) {
return entry.key;
}
}
if (!fallbackToAll) {
return null;
}
}
for (const entry of registry) {
if (entry.autoDiscoverableByDefault && entry.check(value)) {
return entry.key;
}
}
return null;
}
const INSERT_BATCH_SIZE = 10;
function initPidDetection(config = {}) {
const root = config.root || document.body;
const orderedRenderers = config.renderers;
let observer = null;
let allRecords = [];
let destroyed = false;
function detectMatches(text) {
var _a;
const DELIMITER_REGEX = /[\s,;()[\]{}<>"']+/;
const matches = [];
let remaining = text;
let offset = 0;
while (remaining.length > 0) {
const delimMatch = DELIMITER_REGEX.exec(remaining);
let token;
let tokenStart;
if (delimMatch === null) {
token = remaining;
tokenStart = offset;
remaining = '';
}
else {
if (delimMatch.index > 0) {
token = remaining.substring(0, delimMatch.index);
tokenStart = offset;
}
else {
offset += delimMatch[0].length;
remaining = remaining.substring(delimMatch[0].length);
continue;
}
offset += delimMatch.index + delimMatch[0].length;
remaining = remaining.substring(delimMatch.index + delimMatch[0].length);
}
if (token.length < 2)
continue;
const { sanitized, leadingStripped } = sanitizeToken(token);
if (sanitized.length < 2)
continue;
const rendererKey = detectBestFit(sanitized, orderedRenderers, (_a = config.fallbackToAll) !== null && _a !== void 0 ? _a : true);
if (rendererKey !== null) {
matches.push({
start: tokenStart + leadingStripped,
end: tokenStart + leadingStripped + sanitized.length,
value: sanitized,
rendererKey,
});
}
}
return matches;
}
async function runScan() {
if (destroyed)
return;
const textNodes = await scanDom(root, config.exclude);
const batches = chunkArray(textNodes, INSERT_BATCH_SIZE);
for (const batch of batches) {
if (destroyed)
return;
await new Promise((resolve) => {
const requestIdle = typeof requestIdleCallback !== 'undefined'
? requestIdleCallback
: (cb) => setTimeout(cb, 0);
requestIdle(async () => {
for (const scannedNode of batch) {
if (destroyed)
break;
if (!scannedNode.textNode.parentNode)
continue;
const matches = detectMatches(scannedNode.text);
if (matches.length > 0) {
const records = replaceMatches(scannedNode.textNode, matches, config);
allRecords.push(...records);
}
}
resolve();
});
});
}
}
if (config.observe) {
observer = new MutationObserver((mutations) => {
var _a;
if (destroyed)
return;
for (const mutation of mutations) {
for (const node of Array.from(mutation.addedNodes)) {
if (node.nodeType === Node.ELEMENT_NODE) {
const element = node;
if ((_a = element.classList) === null || _a === void 0 ? void 0 : _a.contains('pid-auto-detect-wrapper'))
continue;
if (element.tagName === 'PID-COMPONENT')
continue;
scanDom(element, config.exclude).then(async (textNodes) => {
for (const scannedNode of textNodes) {
if (destroyed)
break;
if (!scannedNode.textNode.parentNode)
continue;
const matches = detectMatches(scannedNode.text);
if (matches.length > 0) {
const records = replaceMatches(scannedNode.textNode, matches, config);
allRecords.push(...records);
}
}
});
}
}
}
});
observer.observe(root, {
childList: true,
subtree: true,
});
}
runScan().then(r => void 0).catch(e => console.error('Error during initial PID detection scan:', e));
return {
stop() {
if (observer) {
observer.disconnect();
}
},
rescan() {
if (!destroyed) {
runScan().then(r => void 0).catch(e => console.error('Error during PID detection rescan:', e));
}
},
destroy() {
destroyed = true;
if (observer) {
observer.disconnect();
observer = null;
}
restoreOriginalText(allRecords);
allRecords = [];
},
};
}
function chunkArray(arr, size) {
const chunks = [];
for (let i = 0; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size));
}
return chunks;
}
exports.ISBNType = PID.ISBNType;
exports.PID = PID.PID;
exports.PIDDataType = PID.PIDDataType;
exports.PIDRecord = PID.PIDRecord;
exports.initPidDetection = initPidDetection;
//# sourceMappingURL=index.cjs.js.map
//# sourceMappingURL=index.cjs.js.map