Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 19 additions & 10 deletions site/lib/src/components/common/client/copy_button.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// found in the LICENSE file.

import 'package:jaspr/jaspr.dart';

import 'package:universal_web/web.dart' as web;

import '../button.dart';
Expand All @@ -30,23 +29,33 @@ class _CopyButtonState extends State<CopyButton> {
String? content;
bool _copied = false;

static final RegExp _terminalReplacementPattern = RegExp(
r'^(\s*\$\s*)|(PS\s+)?(C:\\(.*)>\s*)',
multiLine: true,
);

@override
void initState() {
if (kIsWeb) {
// Extract the code content and unhide the copy button on the client.
context.binding.addPostFrameCallback(() {
setState(() {
content = buttonKey.currentNode
final codeElement = buttonKey.currentNode
?.closest('.code-block-wrapper')
?.querySelector('pre code')
?.textContent
?.replaceAll(_terminalReplacementPattern, '')
.replaceAll('\u200B', ''); // Remove zero-width spaces
?.cloneNode(true);
if (codeElement == null) return;

// Filter out hidden elements like the terminal sign or folding icons.
final iterator = web.document.createNodeIterator(
codeElement,
/* NodeFilter.SHOW_ELEMENT */ 1,
);
web.Node? currentNode;
while ((currentNode = iterator.nextNode()) != null) {
final element = currentNode as web.Element;
if (element.getAttribute('aria-hidden') == 'true') {
element.remove();
}
}

// Remove zero-width spaces
content = codeElement.textContent?.replaceAll('\u200B', '');
});

assert(
Expand Down
Loading