|
| 1 | +/* |
| 2 | + * Copyright 2026 znai maintainers |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.testingisdocumenting.znai.diagrams.mermaid; |
| 18 | + |
| 19 | +import org.testingisdocumenting.znai.structure.DocStructure; |
| 20 | +import org.testingisdocumenting.znai.structure.DocUrl; |
| 21 | +import org.testingisdocumenting.znai.utils.UrlUtils; |
| 22 | + |
| 23 | +import java.nio.file.Path; |
| 24 | +import java.util.regex.Matcher; |
| 25 | +import java.util.regex.Pattern; |
| 26 | + |
| 27 | +class MermaidLinkResolver { |
| 28 | + // matches: click nodeId "url" or click nodeId href "url" |
| 29 | + private static final Pattern CLICK_URL_PATTERN = Pattern.compile( |
| 30 | + "click\\s+\\S+\\s+(?:href\\s+)?\"([^\"]+)\""); |
| 31 | + |
| 32 | + private MermaidLinkResolver() { |
| 33 | + } |
| 34 | + |
| 35 | + static String validateAndResolveLinks(DocStructure docStructure, Path markupPath, String mermaidContent) { |
| 36 | + Matcher matcher = CLICK_URL_PATTERN.matcher(mermaidContent); |
| 37 | + StringBuilder result = new StringBuilder(); |
| 38 | + while (matcher.find()) { |
| 39 | + String url = matcher.group(1); |
| 40 | + if (UrlUtils.isExternal(url)) { |
| 41 | + matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group())); |
| 42 | + continue; |
| 43 | + } |
| 44 | + |
| 45 | + DocUrl docUrl = new DocUrl(url); |
| 46 | + docStructure.validateUrl(markupPath, "inside mermaid diagram", docUrl); |
| 47 | + |
| 48 | + String resolvedUrl = docStructure.createUrl(markupPath, docUrl); |
| 49 | + String replacement = matcher.group().replace("\"" + url + "\"", "\"" + resolvedUrl + "\""); |
| 50 | + matcher.appendReplacement(result, Matcher.quoteReplacement(replacement)); |
| 51 | + } |
| 52 | + matcher.appendTail(result); |
| 53 | + return result.toString(); |
| 54 | + } |
| 55 | +} |
0 commit comments