Line data Source code
1 : import type { LGraph, Subgraph } from '@/lib/litegraph/src/litegraph'
2 : import { formatDate } from '@/utils/formatUtil'
3 : import { collectAllNodes } from '@/utils/graphTraversalUtil'
4 :
5 134 : export function applyTextReplacements(
6 : graph: LGraph | Subgraph,
7 : value: string
8 : ): string {
9 134 : const allNodes = collectAllNodes(graph)
10 :
11 134 : return value.replace(/%([^%]+)%/g, function (match, text) {
12 1 : const isDate = text.startsWith('date:')
13 1 : const fallbackReplacement = isDate
14 : ? formatDate(text.substring(5), new Date())
15 : : match
16 :
17 1 : const split = text.split('.')
18 1 : if (split.length !== 2) {
19 0 : if (!isDate && text !== 'width' && text !== 'height') {
20 0 : console.warn('Invalid replacement pattern', text)
21 : }
22 0 : return fallbackReplacement
23 : }
24 :
25 1 : let nodes = allNodes.filter(
26 : (n) => n.properties['Node name for S&R'] === split[0]
27 : )
28 1 : if (!nodes.length) {
29 0 : nodes = allNodes.filter((n) => n.title === split[0])
30 : }
31 1 : if (!nodes.length) {
32 0 : if (!isDate) console.warn('Unable to find node', split[0])
33 0 : return fallbackReplacement
34 : }
35 :
36 1 : if (nodes.length > 1) {
37 0 : console.warn('Multiple nodes matched', split[0], 'using first match')
38 : }
39 :
40 1 : const node = nodes[0]
41 :
42 1 : const widget = node.widgets?.find((w) => w.name === split[1])
43 1 : if (!widget) {
44 0 : console.warn('Unable to find widget', split[1], 'on node', split[0], node)
45 0 : return match
46 : }
47 :
48 1 : return ((widget.value ?? '') + '').replaceAll(
49 : // oxlint-disable-next-line no-control-regex
50 : /[/?<>\\:*|"\x00-\x1F\x7F]/g,
51 : '_'
52 : )
53 : })
54 : }
|