Skip to content

Commit 49af000

Browse files
committed
filter out hidden elements when copying code
1 parent 12d6528 commit 49af000

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

site/lib/src/components/common/client/copy_button.dart

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
// found in the LICENSE file.
44

55
import 'package:jaspr/jaspr.dart';
6-
6+
import 'package:universal_web/js_interop.dart';
77
import 'package:universal_web/web.dart' as web;
88

99
import '../button.dart';
@@ -30,23 +30,31 @@ class _CopyButtonState extends State<CopyButton> {
3030
String? content;
3131
bool _copied = false;
3232

33-
static final RegExp _terminalReplacementPattern = RegExp(
34-
r'^(\s*\$\s*)|(PS\s+)?(C:\\(.*)>\s*)',
35-
multiLine: true,
36-
);
37-
3833
@override
3934
void initState() {
4035
if (kIsWeb) {
4136
// Extract the code content and unhide the copy button on the client.
4237
context.binding.addPostFrameCallback(() {
4338
setState(() {
44-
content = buttonKey.currentNode
39+
final codeElement = buttonKey.currentNode
4540
?.closest('.code-block-wrapper')
4641
?.querySelector('pre code')
47-
?.textContent
48-
?.replaceAll(_terminalReplacementPattern, '')
49-
.replaceAll('\u200B', ''); // Remove zero-width spaces
42+
?.cloneNode(true);
43+
if (codeElement == null) return;
44+
45+
// Filter out hidden elements like the terminal sign or folding icons.
46+
final iterator = web.document.createNodeIterator(codeElement);
47+
web.Node? currentNode;
48+
while ((currentNode = iterator.nextNode()) != null) {
49+
if (currentNode.isA<web.Element>() &&
50+
(currentNode as web.Element).getAttribute('aria-hidden') ==
51+
'true') {
52+
currentNode.remove();
53+
}
54+
}
55+
56+
// Remove zero-width spaces
57+
content = codeElement.textContent?.replaceAll('\u200B', '');
5058
});
5159

5260
assert(

0 commit comments

Comments
 (0)