@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.
168 lines (167 loc) • 6.48 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.
*
*/
import { scanDom } from "./DomScanner";
import { replaceMatches, restoreOriginalText } from "./TextReplacer";
import { detectBestFit, sanitizeToken } from "./detection-registry";
const INSERT_BATCH_SIZE = 10;
export 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 r).catch(e => console.error('Error during initial PID detection scan:', e));
return {
stop() {
if (observer) {
observer.disconnect();
}
},
rescan() {
if (!destroyed) {
runScan().then(r => void r).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;
}
//# sourceMappingURL=initPidDetection.js.map