Skip to content

Commit 0c8bb63

Browse files
committed
Merge branch 'feat/smart-text-replacer-and-linebreaks' into chore/all-my-stuffs
# Conflicts: # src/tools/index.ts
2 parents 8fc2d72 + 1702fc3 commit 0c8bb63

File tree

3 files changed

+214
-0
lines changed

3 files changed

+214
-0
lines changed

src/tools/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { tool as dnsQueries } from './dns-queries';
55
import { tool as icoConverter } from './ico-converter';
66
import { tool as jsonEditor } from './json-editor';
77
import { tool as slaCalculator } from './sla-calculator';
8+
import { tool as smartTextReplacer } from './smart-text-replacer';
89
import { tool as emailNormalizer } from './email-normalizer';
910
import { tool as bounceParser } from './bounce-parser';
1011
import { tool as codeHighlighter } from './code-highlighter';
@@ -375,6 +376,7 @@ export const toolsByCategory: ToolCategory[] = [
375376
textDiff,
376377
numeronymGenerator,
377378
aiPromptSplitter,
379+
smartTextReplacer,
378380
asciiTextDrawer,
379381
pasteAsMarkdown,
380382
iso3166Searcher,
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { Search } from '@vicons/tabler';
2+
import { defineTool } from '../tool';
3+
4+
export const tool = defineTool({
5+
name: 'Smart Text Replacer and Linebreaker',
6+
path: '/smart-text-replacer',
7+
description: 'Search and replace a word on single or multiple occurrences just like windows notepad search and replace. Also allows to manage linebreaking and text splitting',
8+
keywords: ['smart', 'text-replacer', 'linebreak', 'remove', 'add', 'split', 'search', 'replace'],
9+
component: () => import('./smart-text-replacer.vue'),
10+
icon: Search,
11+
createdAt: new Date('2024-04-03'),
12+
});
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
<script setup lang="ts">
2+
import { useCopy } from '@/composable/copy';
3+
4+
const str = ref('Lorem ipsum dolor sit amet DOLOR Lorem ipsum dolor sit amet DOLOR');
5+
const findWhat = ref('');
6+
const replaceWith = ref('');
7+
const matchCase = ref(false);
8+
const keepLineBreaks = ref(true);
9+
const addLineBreakPlace = ref('before');
10+
const addLineBreakRegex = ref('');
11+
const splitEveryCharacterCounts = ref(0);
12+
13+
// Tracks the index of the currently active highlight.
14+
const currentActiveIndex = ref(0);
15+
// Tracks the total number of matches found to cycle through them.
16+
const totalMatches = ref(0);
17+
18+
const highlightedText = computed(() => {
19+
const findWhatValue = findWhat.value;
20+
let strValue = str.value;
21+
22+
if (!strValue) {
23+
return strValue;
24+
}
25+
26+
if (!keepLineBreaks.value) {
27+
strValue = strValue.replace(/\r?\n/g, '');
28+
}
29+
30+
if (addLineBreakRegex.value) {
31+
const addLBRegex = new RegExp(addLineBreakRegex.value, matchCase.value ? 'g' : 'gi');
32+
if (addLineBreakPlace.value === 'before') {
33+
strValue = strValue.replace(addLBRegex, m => `\n${m}`);
34+
}
35+
else if (addLineBreakPlace.value === 'after') {
36+
strValue = strValue.replace(addLBRegex, m => `${m}\n`);
37+
}
38+
else if (addLineBreakPlace.value === 'place') {
39+
strValue = strValue.replace(addLBRegex, '\n');
40+
}
41+
}
42+
if (splitEveryCharacterCounts.value) {
43+
strValue = strValue.replace(new RegExp(`[^\n]{${splitEveryCharacterCounts.value}}`, 'g'), m => `${m}\n`);
44+
}
45+
46+
if (!findWhatValue) {
47+
return strValue;
48+
}
49+
50+
const regex = new RegExp(findWhatValue, matchCase.value ? 'g' : 'gi');
51+
let index = 0;
52+
const newStr = strValue.replace(regex, (match) => {
53+
index++;
54+
return `<span class="${match === findWhatValue ? 'highlight' : 'outline'}">${match}</span>`;
55+
});
56+
57+
totalMatches.value = index;
58+
// Reset to -1 to ensure the first match is highlighted upon next search
59+
currentActiveIndex.value = -1;
60+
return newStr;
61+
});
62+
63+
// Automatically highlight the first occurrence after any change
64+
watchEffect(async () => {
65+
if (highlightedText.value) {
66+
await nextTick();
67+
updateHighlighting();
68+
}
69+
});
70+
71+
watch(matchCase, () => {
72+
// Use nextTick to wait for the DOM to update after highlightedText re-reaction
73+
nextTick().then(() => {
74+
const matches = document.querySelectorAll('.outline, .highlight');
75+
if (matches.length === 0) {
76+
// No matches after change, reset
77+
currentActiveIndex.value = -1;
78+
totalMatches.value = 0;
79+
}
80+
else if (matches.length <= currentActiveIndex.value || currentActiveIndex.value === -1) {
81+
// Current selection is out of range or reset, select the first match
82+
currentActiveIndex.value = 0;
83+
updateHighlighting(); // Ensure correct highlighting
84+
}
85+
else {
86+
// The current selection is still valid, ensure it's highlighted correctly
87+
updateHighlighting(); // This might need adjustment to not advance the index
88+
}
89+
});
90+
});
91+
92+
// Function to add active highlighting
93+
function updateHighlighting() {
94+
currentActiveIndex.value = (currentActiveIndex.value + 1) % totalMatches.value;
95+
const matches = document.querySelectorAll('.outline, .highlight');
96+
matches.forEach((match, index) => {
97+
match.className = index === currentActiveIndex.value ? 'highlight' : 'outline';
98+
});
99+
}
100+
101+
function replaceSelected() {
102+
const matches = document.querySelectorAll('.outline, .highlight');
103+
if (matches.length > currentActiveIndex.value) {
104+
const selectedMatch = matches[currentActiveIndex.value];
105+
if (selectedMatch) {
106+
const newText = replaceWith.value;
107+
selectedMatch.textContent = newText;
108+
selectedMatch.classList.remove('highlight');
109+
currentActiveIndex.value--;
110+
totalMatches.value--;
111+
}
112+
}
113+
updateHighlighting();
114+
}
115+
116+
function replaceAll() {
117+
const matches = document.querySelectorAll('.outline, .highlight');
118+
matches.forEach((match) => {
119+
match.textContent = replaceWith.value;
120+
match.classList.remove('highlight');
121+
match.classList.remove('outline');
122+
});
123+
currentActiveIndex.value = -1;
124+
totalMatches.value = matches.length;
125+
}
126+
127+
function findNext() {
128+
updateHighlighting();
129+
}
130+
131+
const { copy } = useCopy({ source: highlightedText });
132+
</script>
133+
134+
<template>
135+
<div>
136+
<c-input-text v-model:value="str" raw-text placeholder="Enter text here..." label="Text to search and replace:" clearable multiline rows="10" />
137+
138+
<div mt-4 w-full flex gap-10px>
139+
<div flex-1>
140+
<div>Find what:</div>
141+
<c-input-text v-model:value="findWhat" placeholder="Search regex" @keyup.enter="findNext()" />
142+
</div>
143+
<div flex-1>
144+
<div>Replace with:</div>
145+
<c-input-text v-model:value="replaceWith" placeholder="Replacement expression" @keyup.enter="replaceSelected()" />
146+
</div>
147+
</div>
148+
149+
<n-space mt-4 gap-1 align="baseline" justify="space-between">
150+
<c-button @click="findNext()">
151+
<label>Find Next</label>
152+
</c-button>
153+
<c-button @click="replaceSelected()">
154+
<label>Replace</label>
155+
</c-button>
156+
<c-button @click="replaceAll()">
157+
<label>Replace All</label>
158+
</c-button>
159+
<n-checkbox v-model:checked="matchCase">
160+
<label>Match case</label>
161+
</n-checkbox>
162+
<n-checkbox v-model:checked="keepLineBreaks">
163+
<label>Keep linebreaks</label>
164+
</n-checkbox>
165+
</n-space>
166+
167+
<n-divider />
168+
169+
<div mt-4 w-full flex items-baseline gap-10px>
170+
<c-select
171+
v-model:value="addLineBreakPlace"
172+
:options="[{ value: 'before', label: 'Add linebreak before' }, { value: 'after', label: 'Add linebreak after' }, { value: 'place', label: 'Add linebreak in place of' }]"
173+
/>
174+
175+
<c-input-text
176+
v-model:value="addLineBreakRegex"
177+
placeholder="Split text regex"
178+
/>
179+
</div>
180+
<div mt-4 w-full flex items-baseline gap-10px>
181+
<n-form-item label="Split every characters:" label-placement="left">
182+
<n-input-number v-model:value="splitEveryCharacterCounts" :min="0" />
183+
</n-form-item>
184+
</div>
185+
<c-card v-if="highlightedText" mt-60px max-w-600px flex items-center gap-5px font-mono>
186+
<!-- //NOSONAR --><div flex-1 break-anywhere text-wrap style="white-space: pre-wrap" v-html="highlightedText" />
187+
188+
<c-button @click="copy()">
189+
<icon-mdi:content-copy />
190+
</c-button>
191+
</c-card>
192+
</div>
193+
</template>
194+
195+
<style lang="less">
196+
.highlight {
197+
background-color: #ff0;
198+
color: black;
199+
}
200+
</style>

0 commit comments

Comments
 (0)