Merge branch 'main' into truncate

This commit is contained in:
Chesterkxng
2024-07-09 21:23:35 +00:00
10 changed files with 563 additions and 221 deletions

149
.idea/workspace.xml generated
View File

@@ -4,7 +4,14 @@
<option name="autoReloadType" value="SELECTIVE" /> <option name="autoReloadType" value="SELECTIVE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="b30e2810-c4c1-4aad-b134-794e52cc1c7d" name="Changes" comment="feat: playwright report" /> <list default="true" id="b30e2810-c4c1-4aad-b134-794e52cc1c7d" name="Changes" comment="feat: find most popular ui">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/components/options/SelectWithDesc.tsx" beforeDir="false" afterPath="$PROJECT_DIR$/src/components/options/SelectWithDesc.tsx" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/components/result/ToolTextResult.tsx" beforeDir="false" afterPath="$PROJECT_DIR$/src/components/result/ToolTextResult.tsx" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/pages/list/find-most-popular/find-most-popular.service.test.ts" beforeDir="false" afterPath="$PROJECT_DIR$/src/pages/list/find-most-popular/find-most-popular.service.test.ts" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/pages/list/sort/index.tsx" beforeDir="false" afterPath="$PROJECT_DIR$/src/pages/list/sort/index.tsx" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/utils/string.ts" beforeDir="false" afterPath="$PROJECT_DIR$/src/utils/string.ts" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
@@ -40,44 +47,44 @@
<option name="hideEmptyMiddlePackages" value="true" /> <option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" /> <option name="showLibraryContents" value="true" />
</component> </component>
<component name="PropertiesComponent"><![CDATA[{ <component name="PropertiesComponent">{
"keyToString": { &quot;keyToString&quot;: {
"ASKED_ADD_EXTERNAL_FILES": "true", &quot;ASKED_ADD_EXTERNAL_FILES&quot;: &quot;true&quot;,
"ASKED_SHARE_PROJECT_CONFIGURATION_FILES": "true", &quot;ASKED_SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;,
"Playwright.JoinText Component.executor": "Run", &quot;Playwright.JoinText Component.executor&quot;: &quot;Run&quot;,
"Playwright.JoinText Component.should merge text pieces with specified join character.executor": "Run", &quot;Playwright.JoinText Component.should merge text pieces with specified join character.executor&quot;: &quot;Run&quot;,
"RunOnceActivity.OpenProjectViewOnStart": "true", &quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
"RunOnceActivity.ShowReadmeOnStart": "true", &quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
"Vitest.compute function (1).executor": "Run", &quot;Vitest.compute function (1).executor&quot;: &quot;Run&quot;,
"Vitest.compute function.executor": "Run", &quot;Vitest.compute function.executor&quot;: &quot;Run&quot;,
"Vitest.mergeText.executor": "Run", &quot;Vitest.mergeText.executor&quot;: &quot;Run&quot;,
"Vitest.mergeText.should merge lines and preserve blank lines when deleteBlankLines is false.executor": "Run", &quot;Vitest.mergeText.should merge lines and preserve blank lines when deleteBlankLines is false.executor&quot;: &quot;Run&quot;,
"Vitest.mergeText.should merge lines, preserve blank lines and trailing spaces when both deleteBlankLines and deleteTrailingSpaces are false.executor": "Run", &quot;Vitest.mergeText.should merge lines, preserve blank lines and trailing spaces when both deleteBlankLines and deleteTrailingSpaces are false.executor&quot;: &quot;Run&quot;,
"git-widget-placeholder": "main", &quot;git-widget-placeholder&quot;: &quot;main&quot;,
"ignore.virus.scanning.warn.message": "true", &quot;ignore.virus.scanning.warn.message&quot;: &quot;true&quot;,
"kotlin-language-version-configured": "true", &quot;kotlin-language-version-configured&quot;: &quot;true&quot;,
"last_opened_file_path": "C:/Users/HP/IdeaProjects/omni-tools/src/assets", &quot;last_opened_file_path&quot;: &quot;C:/Users/HP/IdeaProjects/omni-tools/src/components/options&quot;,
"node.js.detected.package.eslint": "true", &quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
"node.js.detected.package.tslint": "true", &quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
"node.js.selected.package.eslint": "(autodetect)", &quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
"node.js.selected.package.tslint": "(autodetect)", &quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
"nodejs_package_manager_path": "npm", &quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
"npm.dev.executor": "Run", &quot;npm.dev.executor&quot;: &quot;Run&quot;,
"npm.lint.executor": "Run", &quot;npm.lint.executor&quot;: &quot;Run&quot;,
"npm.prebuild.executor": "Run", &quot;npm.prebuild.executor&quot;: &quot;Run&quot;,
"npm.script:create:tool.executor": "Run", &quot;npm.script:create:tool.executor&quot;: &quot;Run&quot;,
"npm.test.executor": "Run", &quot;npm.test.executor&quot;: &quot;Run&quot;,
"npm.test:e2e.executor": "Run", &quot;npm.test:e2e.executor&quot;: &quot;Run&quot;,
"npm.test:e2e:run.executor": "Run", &quot;npm.test:e2e:run.executor&quot;: &quot;Run&quot;,
"prettierjs.PrettierConfiguration.Package": "C:\\Users\\HP\\IdeaProjects\\omni-tools\\node_modules\\prettier", &quot;prettierjs.PrettierConfiguration.Package&quot;: &quot;C:\\Users\\HP\\IdeaProjects\\omni-tools\\node_modules\\prettier&quot;,
"project.structure.last.edited": "Problems", &quot;project.structure.last.edited&quot;: &quot;Problems&quot;,
"project.structure.proportion": "0.0", &quot;project.structure.proportion&quot;: &quot;0.0&quot;,
"project.structure.side.proportion": "0.2", &quot;project.structure.side.proportion&quot;: &quot;0.2&quot;,
"settings.editor.selected.configurable": "settings.typescriptcompiler", &quot;settings.editor.selected.configurable&quot;: &quot;settings.typescriptcompiler&quot;,
"ts.external.directory.path": "C:\\Users\\HP\\IdeaProjects\\omni-tools\\node_modules\\typescript\\lib", &quot;ts.external.directory.path&quot;: &quot;C:\\Users\\HP\\IdeaProjects\\omni-tools\\node_modules\\typescript\\lib&quot;,
"vue.rearranger.settings.migration": "true" &quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
} }
}]]></component> }</component>
<component name="ReactDesignerToolWindowState"> <component name="ReactDesignerToolWindowState">
<option name="myId2Visible"> <option name="myId2Visible">
<map> <map>
@@ -89,11 +96,11 @@
</component> </component>
<component name="RecentsManager"> <component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS"> <key name="CopyFile.RECENT_KEYS">
<recent name="C:\Users\HP\IdeaProjects\omni-tools\src\components\options" />
<recent name="C:\Users\HP\IdeaProjects\omni-tools\src\assets" /> <recent name="C:\Users\HP\IdeaProjects\omni-tools\src\assets" />
<recent name="C:\Users\HP\IdeaProjects\omni-tools\src\pages\string" /> <recent name="C:\Users\HP\IdeaProjects\omni-tools\src\pages\string" />
<recent name="C:\Users\HP\IdeaProjects\omni-tools\src\pages\string\split" /> <recent name="C:\Users\HP\IdeaProjects\omni-tools\src\pages\string\split" />
<recent name="C:\Users\HP\IdeaProjects\omni-tools\src\pages\images" /> <recent name="C:\Users\HP\IdeaProjects\omni-tools\src\pages\images" />
<recent name="C:\Users\HP\IdeaProjects\omni-tools\public" />
</key> </key>
<key name="MoveFile.RECENT_KEYS"> <key name="MoveFile.RECENT_KEYS">
<recent name="C:\Users\HP\IdeaProjects\omni-tools\src\components" /> <recent name="C:\Users\HP\IdeaProjects\omni-tools\src\components" />
@@ -102,7 +109,7 @@
<recent name="C:\Users\HP\IdeaProjects\omni-tools\src\tools" /> <recent name="C:\Users\HP\IdeaProjects\omni-tools\src\tools" />
</key> </key>
</component> </component>
<component name="RunManager" selected="npm.test:e2e"> <component name="RunManager" selected="npm.dev">
<configuration name="JoinText Component.should merge text pieces with specified join character" type="JavaScriptTestRunnerPlaywright" temporary="true" nameIsGenerated="true"> <configuration name="JoinText Component.should merge text pieces with specified join character" type="JavaScriptTestRunnerPlaywright" temporary="true" nameIsGenerated="true">
<node-interpreter value="project" /> <node-interpreter value="project" />
<playwright-package value="$PROJECT_DIR$/node_modules/@playwright/test" /> <playwright-package value="$PROJECT_DIR$/node_modules/@playwright/test" />
@@ -158,11 +165,11 @@
</configuration> </configuration>
<recent_temporary> <recent_temporary>
<list> <list>
<item itemvalue="npm.dev" />
<item itemvalue="npm.test:e2e" /> <item itemvalue="npm.test:e2e" />
<item itemvalue="Playwright.JoinText Component.should merge text pieces with specified join character" /> <item itemvalue="Playwright.JoinText Component.should merge text pieces with specified join character" />
<item itemvalue="npm.test" /> <item itemvalue="npm.test" />
<item itemvalue="npm.lint" /> <item itemvalue="npm.lint" />
<item itemvalue="npm.dev" />
</list> </list>
</recent_temporary> </recent_temporary>
</component> </component>
@@ -198,30 +205,8 @@
<workItem from="1719475764139" duration="14903000" /> <workItem from="1719475764139" duration="14903000" />
<workItem from="1719492452780" duration="8000" /> <workItem from="1719492452780" duration="8000" />
<workItem from="1719496624579" duration="6148000" /> <workItem from="1719496624579" duration="6148000" />
</task> <workItem from="1720542757452" duration="5355000" />
<task id="LOCAL-00038" summary="fix: readme"> <workItem from="1720557527691" duration="1135000" />
<option name="closed" value="true" />
<created>1719171905785</created>
<option name="number" value="00038" />
<option name="presentableId" value="LOCAL-00038" />
<option name="project" value="LOCAL" />
<updated>1719171905785</updated>
</task>
<task id="LOCAL-00039" summary="fix: build">
<option name="closed" value="true" />
<created>1719172147719</created>
<option name="number" value="00039" />
<option name="presentableId" value="LOCAL-00039" />
<option name="project" value="LOCAL" />
<updated>1719172147719</updated>
</task>
<task id="LOCAL-00040" summary="chore: CODEOWNERS">
<option name="closed" value="true" />
<created>1719184899883</created>
<option name="number" value="00040" />
<option name="presentableId" value="LOCAL-00040" />
<option name="project" value="LOCAL" />
<updated>1719184899883</updated>
</task> </task>
<task id="LOCAL-00041" summary="ci: fix"> <task id="LOCAL-00041" summary="ci: fix">
<option name="closed" value="true" /> <option name="closed" value="true" />
@@ -591,7 +576,31 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1719600693979</updated> <updated>1719600693979</updated>
</task> </task>
<option name="localTasksCounter" value="87" /> <task id="LOCAL-00087" summary="chore: idea config">
<option name="closed" value="true" />
<created>1719600739052</created>
<option name="number" value="00087" />
<option name="presentableId" value="LOCAL-00087" />
<option name="project" value="LOCAL" />
<updated>1719600739052</updated>
</task>
<task id="LOCAL-00088" summary="feat: sort list">
<option name="closed" value="true" />
<created>1720545582958</created>
<option name="number" value="00088" />
<option name="presentableId" value="LOCAL-00088" />
<option name="project" value="LOCAL" />
<updated>1720545582958</updated>
</task>
<task id="LOCAL-00089" summary="feat: find most popular ui">
<option name="closed" value="true" />
<created>1720546921899</created>
<option name="number" value="00089" />
<option name="presentableId" value="LOCAL-00089" />
<option name="project" value="LOCAL" />
<updated>1720546921899</updated>
</task>
<option name="localTasksCounter" value="90" />
<servers /> <servers />
</component> </component>
<component name="TypeScriptGeneratedFilesManager"> <component name="TypeScriptGeneratedFilesManager">
@@ -635,9 +644,6 @@
<option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="false" /> <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="false" />
<option name="CHECK_NEW_TODO" value="false" /> <option name="CHECK_NEW_TODO" value="false" />
<option name="ADD_EXTERNAL_FILES_SILENTLY" value="true" /> <option name="ADD_EXTERNAL_FILES_SILENTLY" value="true" />
<MESSAGE value="fix: readme" />
<MESSAGE value="refactor: tool input and result" />
<MESSAGE value="feat: create transparent png" />
<MESSAGE value="fix: ToolFileInput.tsx" /> <MESSAGE value="fix: ToolFileInput.tsx" />
<MESSAGE value="fix: generate numbers" /> <MESSAGE value="fix: generate numbers" />
<MESSAGE value="fix: merging branches" /> <MESSAGE value="fix: merging branches" />
@@ -660,7 +666,10 @@
<MESSAGE value="chore: jimp types" /> <MESSAGE value="chore: jimp types" />
<MESSAGE value="fix: package.json" /> <MESSAGE value="fix: package.json" />
<MESSAGE value="feat: playwright report" /> <MESSAGE value="feat: playwright report" />
<option name="LAST_COMMIT_MESSAGE" value="feat: playwright report" /> <MESSAGE value="chore: idea config" />
<MESSAGE value="feat: sort list" />
<MESSAGE value="feat: find most popular ui" />
<option name="LAST_COMMIT_MESSAGE" value="feat: find most popular ui" />
</component> </component>
<component name="XSLT-Support.FileAssociations.UIState"> <component name="XSLT-Support.FileAssociations.UIState">
<expand /> <expand />

View File

@@ -0,0 +1,50 @@
import React from 'react';
import {
Box,
MenuItem,
Select,
SelectChangeEvent,
Typography
} from '@mui/material';
interface Option<T extends string | boolean> {
label: string;
value: T;
}
const SelectWithDesc = <T extends string | boolean>({
selected,
options,
onChange,
description
}: {
selected: T;
options: Option<T>[];
onChange: (value: T) => void;
description: string;
}) => {
const handleChange = (event: SelectChangeEvent<T>) => {
const newValue =
typeof selected === 'boolean'
? event.target.value === 'true'
: event.target.value;
onChange(newValue as T);
};
return (
<Box>
<Select value={selected} onChange={handleChange}>
{options.map((option) => (
<MenuItem key={option.label} value={option.value.toString()}>
{option.label}
</MenuItem>
))}
</Select>
<Typography fontSize={12} mt={1}>
{description}
</Typography>
</Box>
);
};
export default SelectWithDesc;

View File

@@ -15,7 +15,7 @@ export default function ToolOptionGroups({
return ( return (
<Grid container spacing={2}> <Grid container spacing={2}>
{groups.map((group) => ( {groups.map((group) => (
<Grid item xs={12} md={6} key={group.title}> <Grid item xs={12} md={4} key={group.title}>
<Typography mb={1} fontSize={22}> <Typography mb={1} fontSize={22}>
{group.title} {group.title}
</Typography> </Typography>

View File

@@ -1,8 +1,9 @@
import { Box, TextField } from '@mui/material'; import { Box, TextField } from '@mui/material';
import React, { useContext } from 'react'; import React, { useContext, useEffect } from 'react';
import { CustomSnackBarContext } from '../../contexts/CustomSnackBarContext'; import { CustomSnackBarContext } from '../../contexts/CustomSnackBarContext';
import InputHeader from '../InputHeader'; import InputHeader from '../InputHeader';
import ResultFooter from './ResultFooter'; import ResultFooter from './ResultFooter';
import { replaceSpecialCharacters } from '../../utils/string';
export default function ToolTextResult({ export default function ToolTextResult({
title = 'Result', title = 'Result',
@@ -37,7 +38,7 @@ export default function ToolTextResult({
<Box> <Box>
<InputHeader title={title} /> <InputHeader title={title} />
<TextField <TextField
value={value} value={replaceSpecialCharacters(value)}
fullWidth fullWidth
multiline multiline
rows={10} rows={10}

View File

@@ -1,65 +1,105 @@
import { expect, describe, it } from 'vitest'; import { expect, describe, it } from 'vitest';
import { TopItemsList, SplitOperatorType, SortingMethod, DisplayFormat } from './service'; import {
TopItemsList,
SplitOperatorType,
SortingMethod,
DisplayFormat
} from './service';
describe('TopItemsList function', () => { describe('TopItemsList function', () => {
it('should handle sorting alphabetically ignoring case', () => { it('should handle sorting alphabetically ignoring case', () => {
const input = 'Apple,banana,apple,Orange,Banana,apple'; const input = 'Apple,banana,apple,Orange,Banana,apple';
const result = TopItemsList('symbol', 'alphabetic', 'count', ',', input, false, true, false); const result = TopItemsList(
expect(result).toEqual( 'symbol',
'apple: 3\n' + 'alphabetic',
'banana: 2\n' + 'count',
'orange: 1' ',',
); input,
}); false,
true,
false
);
expect(result).toEqual('apple: 3\n' + 'banana: 2\n' + 'orange: 1');
});
it('should handle sorting by count and not ignoring case', () => { it('should handle sorting by count and not ignoring case', () => {
const input = 'apple,banana,apple,orange,banana,apple,Banana'; const input = 'apple,banana,apple,orange,banana,apple,Banana';
const result = TopItemsList('symbol', 'count', 'count', ',', input, false, false, false); const result = TopItemsList(
expect(result).toEqual( 'symbol',
'apple: 3\n' + 'count',
'banana: 2\n' + 'count',
'orange: 1\n' + ',',
'Banana: 1' input,
); false,
}); false,
false
);
expect(result).toEqual(
'apple: 3\n' + 'banana: 2\n' + 'orange: 1\n' + 'Banana: 1'
);
});
it('should handle regex split operator', () => { it('should handle regex split operator', () => {
const input = 'apple123banana456apple789orange012banana345apple678'; const input = 'apple123banana456apple789orange012banana345apple678';
const result = TopItemsList('regex', 'count', 'count', '\\d+', input, false, false, false); const result = TopItemsList(
expect(result).toEqual( 'regex',
'apple: 3\n' + 'count',
'banana: 2\n' + 'count',
'orange: 1' '\\d+',
); input,
}); false,
false,
false
);
expect(result).toEqual('apple: 3\n' + 'banana: 2\n' + 'orange: 1');
});
it('should handle percentage display format', () => { it('should handle percentage display format', () => {
const input = 'apple,banana,apple,orange,banana,apple'; const input = 'apple,banana,apple,orange,banana,apple';
const result = TopItemsList('symbol', 'count', 'percentage', ',', input, false, false, false); const result = TopItemsList(
expect(result).toEqual( 'symbol',
'apple: 3 (50.00%)\n' + 'count',
'banana: 2 (33.33%)\n' + 'percentage',
'orange: 1 (16.67%)' ',',
); input,
}); false,
false,
false
);
expect(result).toEqual(
'apple: 3 (50.00%)\n' + 'banana: 2 (33.33%)\n' + 'orange: 1 (16.67%)'
);
});
it('should handle total display format', () => { it('should handle total display format', () => {
const input = 'apple,banana,apple,orange,banana,apple'; const input = 'apple,banana,apple,orange,banana,apple';
const result = TopItemsList('symbol', 'count', 'total', ',', input, false, false, false); const result = TopItemsList(
expect(result).toEqual( 'symbol',
'apple: 3 (3 / 6)\n' + 'count',
'banana: 2 (2 / 6)\n' + 'total',
'orange: 1 (1 / 6)' ',',
); input,
}); false,
false,
false
);
expect(result).toEqual(
'apple: 3 (3 / 6)\n' + 'banana: 2 (2 / 6)\n' + 'orange: 1 (1 / 6)'
);
});
it('should handle trimming and ignoring empty items', () => { it('should handle trimming and ignoring empty items', () => {
const input = ' apple , banana , apple , orange , banana , apple '; const input = ' apple , banana , apple , orange , banana , apple ';
const result = TopItemsList('symbol', 'count', 'count', ',', input, true, false, true); const result = TopItemsList(
expect(result).toEqual( 'symbol',
'apple: 3\n' + 'count',
'banana: 2\n' + 'count',
'orange: 1' ',',
); input,
}); true,
}); false,
true
);
expect(result).toEqual('apple: 3\n' + 'banana: 2\n' + 'orange: 1');
});
});

View File

@@ -1,11 +1,172 @@
import { Box } from '@mui/material'; import { Box } from '@mui/material';
import React from 'react'; import React, { useState } from 'react';
import ToolTextInput from '../../../components/input/ToolTextInput';
import ToolTextResult from '../../../components/result/ToolTextResult';
import * as Yup from 'yup'; import * as Yup from 'yup';
import ToolOptions from '../../../components/options/ToolOptions';
import {
DisplayFormat,
SortingMethod,
SplitOperatorType,
TopItemsList
} from './service';
import ToolInputAndResult from '../../../components/ToolInputAndResult';
import SimpleRadio from '../../../components/options/SimpleRadio';
import TextFieldWithDesc from '../../../components/options/TextFieldWithDesc';
import CheckboxWithDesc from '../../../components/options/CheckboxWithDesc';
import SelectWithDesc from '../../../components/options/SelectWithDesc';
const initialValues = {
splitSeparatorType: 'symbol' as SplitOperatorType,
sortingMethod: 'alphabetic' as SortingMethod,
displayFormat: 'count' as DisplayFormat,
splitSeparator: ',',
deleteEmptyItems: false,
ignoreItemCase: false,
trimItems: false
};
const splitOperators: {
title: string;
description: string;
type: SplitOperatorType;
}[] = [
{
title: 'Use a Symbol for Splitting',
description: 'Delimit input list items with a character.',
type: 'symbol'
},
{
title: 'Use a Regex for Splitting',
type: 'regex',
description: 'Delimit input list items with a regular expression.'
}
];
const initialValues = {};
const validationSchema = Yup.object({
// splitSeparator: Yup.string().required('The separator is required')
});
export default function FindMostPopular() { export default function FindMostPopular() {
return <Box>Lorem ipsum</Box>; const [input, setInput] = useState<string>('');
} const [result, setResult] = useState<string>('');
const compute = (optionsValues: typeof initialValues, input: any) => {
const {
splitSeparatorType,
splitSeparator,
displayFormat,
sortingMethod,
deleteEmptyItems,
ignoreItemCase,
trimItems
} = optionsValues;
setResult(
TopItemsList(
splitSeparatorType,
sortingMethod,
displayFormat,
splitSeparator,
input,
deleteEmptyItems,
ignoreItemCase,
trimItems
)
);
};
const validationSchema = Yup.object({
// splitSeparator: Yup.string().required('The separator is required')
});
return (
<Box>
<ToolInputAndResult
input={
<ToolTextInput
title={'Input list'}
value={input}
onChange={setInput}
/>
}
result={<ToolTextResult title={'Most popular items'} value={result} />}
/>
<ToolOptions
compute={compute}
getGroups={({ values, updateField }) => [
{
title: 'How to Extract List Items?',
component: (
<Box>
{splitOperators.map(({ title, description, type }) => (
<SimpleRadio
key={type}
onClick={() => updateField('splitSeparatorType', type)}
title={title}
description={description}
checked={values.splitSeparatorType === type}
/>
))}
<TextFieldWithDesc
description={'Set a delimiting symbol or regular expression.'}
value={values.splitSeparator}
onOwnChange={(val) => updateField('splitSeparator', val)}
/>
</Box>
)
},
{
title: 'Item comparison',
component: (
<Box>
<CheckboxWithDesc
title={'Remove empty items'}
description={'Ignore empty items from comparison.'}
checked={values.deleteEmptyItems}
onChange={(value) => updateField('deleteEmptyItems', value)}
/>
<CheckboxWithDesc
title={'Trim top list items'}
description={
'Remove leading and trailing spaces before comparing items'
}
checked={values.trimItems}
onChange={(value) => updateField('trimItems', value)}
/>
<CheckboxWithDesc
title={'Ignore Item Case'}
description={'Compare all list items in lowercase.'}
checked={values.ignoreItemCase}
onChange={(value) => updateField('ignoreItemCase', value)}
/>
</Box>
)
},
{
title: 'Top item output format',
component: (
<Box>
<SelectWithDesc
selected={values.displayFormat}
options={[
{ label: 'Show item percentage', value: 'percentage' },
{ label: 'Show item count', value: 'count' },
{ label: 'Show item total', value: 'total' }
]}
onChange={(value) => updateField('displayFormat', value)}
description={'How to display the most popular list items?'}
/>
<SelectWithDesc
selected={values.sortingMethod}
options={[
{ label: 'Sort Alphabetically', value: 'alphabetic' },
{ label: 'Sort by count', value: 'count' }
]}
onChange={(value) => updateField('sortingMethod', value)}
description={'Select a sorting method.'}
/>
</Box>
)
}
]}
initialValues={initialValues}
input={input}
validationSchema={validationSchema}
/>
</Box>
);
}

View File

@@ -3,105 +3,112 @@ export type DisplayFormat = 'count' | 'percentage' | 'total';
export type SortingMethod = 'count' | 'alphabetic'; export type SortingMethod = 'count' | 'alphabetic';
// Function that takes the array as arg and returns a dict of element occurrences and handle the ignoreItemCase // Function that takes the array as arg and returns a dict of element occurrences and handle the ignoreItemCase
function dictMaker(array: string[], function dictMaker(
ignoreItemCase: boolean array: string[],
ignoreItemCase: boolean
): { [key: string]: number } { ): { [key: string]: number } {
const dict: { [key: string]: number } = {}; const dict: { [key: string]: number } = {};
for (const item of array) { for (const item of array) {
const key = ignoreItemCase ? item.toLowerCase() : item; const key = ignoreItemCase ? item.toLowerCase() : item;
dict[key] = (dict[key] || 0) + 1; dict[key] = (dict[key] || 0) + 1;
} }
return dict; return dict;
} }
// Function that sorts the dict created with dictMaker based on the chosen sorting method // Function that sorts the dict created with dictMaker based on the chosen sorting method
function dictSorter( function dictSorter(
dict: { [key: string]: number }, dict: { [key: string]: number },
sortingMethod: SortingMethod, sortingMethod: SortingMethod
): { [key: string]: number } { ): { [key: string]: number } {
let sortedArray: [string, number][]; let sortedArray: [string, number][];
switch (sortingMethod) { switch (sortingMethod) {
case 'count': case 'count':
sortedArray = Object.entries(dict).sort(([, countA], [, countB]) => countB - countA); sortedArray = Object.entries(dict).sort(
break; ([, countA], [, countB]) => countB - countA
case 'alphabetic': );
sortedArray = Object.entries(dict).sort(([keyA], [keyB]) => { break;
return keyA.localeCompare(keyB) case 'alphabetic':
}); sortedArray = Object.entries(dict).sort(([keyA], [keyB]) => {
break; return keyA.localeCompare(keyB);
default: });
sortedArray = Object.entries(dict); break;
break; default:
} sortedArray = Object.entries(dict);
return Object.fromEntries(sortedArray); break;
}
return Object.fromEntries(sortedArray);
} }
// Function that prepares the output of dictSorter based on the chosen display format // Function that prepares the output of dictSorter based on the chosen display format
function displayFormater( function displayFormater(
dict: { [key: string]: number }, dict: { [key: string]: number },
displayFormat: DisplayFormat displayFormat: DisplayFormat
): string[] { ): string[] {
let formattedOutput: string[] = []; let formattedOutput: string[] = [];
const total = Object.values(dict).reduce((acc, val) => acc + val, 0); const total = Object.values(dict).reduce((acc, val) => acc + val, 0);
switch (displayFormat) { switch (displayFormat) {
case 'percentage': case 'percentage':
Object.entries(dict).forEach(([key, value]) => { Object.entries(dict).forEach(([key, value]) => {
formattedOutput.push(`${key}: ${value} (${((value / total) * 100).toFixed(2)}%)`); formattedOutput.push(
}); `${key}: ${value} (${((value / total) * 100).toFixed(2)}%)`
break; );
case "total": });
Object.entries(dict).forEach(([key, value]) => { break;
formattedOutput.push(`${key}: ${value} (${value} / ${total})`); case 'total':
}); Object.entries(dict).forEach(([key, value]) => {
break; formattedOutput.push(`${key}: ${value} (${value} / ${total})`);
case "count": });
Object.entries(dict).forEach(([key, value]) => { break;
formattedOutput.push(`${key}: ${value}`); case 'count':
}); Object.entries(dict).forEach(([key, value]) => {
break; formattedOutput.push(`${key}: ${value}`);
} });
return formattedOutput; break;
}
return formattedOutput;
} }
export function TopItemsList( export function TopItemsList(
splitOperatorType: SplitOperatorType, splitOperatorType: SplitOperatorType,
sortingMethod: SortingMethod, sortingMethod: SortingMethod,
displayFormat: DisplayFormat, displayFormat: DisplayFormat,
splitSeparator: string, splitSeparator: string,
input: string, input: string,
deleteEmptyItems: boolean, deleteEmptyItems: boolean,
ignoreItemCase: boolean, ignoreItemCase: boolean,
trimItems: boolean trimItems: boolean
): string { ): string {
let array: string[]; let array: string[];
switch (splitOperatorType) { switch (splitOperatorType) {
case 'symbol': case 'symbol':
array = input.split(splitSeparator); array = input.split(splitSeparator);
break; break;
case 'regex': case 'regex':
array = input.split(new RegExp(splitSeparator)).filter(item => item !== ''); array = input
break; .split(new RegExp(splitSeparator))
} .filter((item) => item !== '');
break;
}
// Trim items if required // Trim items if required
if (trimItems) { if (trimItems) {
array = array.map(item => item.trim()); array = array.map((item) => item.trim());
} }
// Delete empty items after initial split // Delete empty items after initial split
if (deleteEmptyItems) { if (deleteEmptyItems) {
array = array.filter(item => item !== ''); array = array.filter((item) => item !== '');
} }
// Transform the array into dict // Transform the array into dict
const unsortedDict = dictMaker(array, ignoreItemCase); const unsortedDict = dictMaker(array, ignoreItemCase);
// Sort the list if required // Sort the list if required
const sortedDict = dictSorter(unsortedDict, sortingMethod); const sortedDict = dictSorter(unsortedDict, sortingMethod);
// Format the output with desired format // Format the output with desired format
const formattedOutput = displayFormater(sortedDict, displayFormat); const formattedOutput = displayFormater(sortedDict, displayFormat);
return formattedOutput.join('\n'); return formattedOutput.join('\n');
} }

View File

@@ -10,4 +10,15 @@ import { tool as listTruncate } from './truncate/meta';
import { tool as listShuffle } from './shuffle/meta'; import { tool as listShuffle } from './shuffle/meta';
import { tool as listSort } from './sort/meta'; import { tool as listSort } from './sort/meta';
export const listTools = [listSort]; export const listTools = [
listSort,
listUnwrap,
listReverse,
listFindUnique,
listFindMostPopular,
listGroup,
listWrap,
listRotate,
listShuffle,
listTruncate
];

View File

@@ -8,6 +8,8 @@ import { Sort, SortingMethod, SplitOperatorType } from './service';
import ToolInputAndResult from '../../../components/ToolInputAndResult'; import ToolInputAndResult from '../../../components/ToolInputAndResult';
import SimpleRadio from '../../../components/options/SimpleRadio'; import SimpleRadio from '../../../components/options/SimpleRadio';
import TextFieldWithDesc from '../../../components/options/TextFieldWithDesc'; import TextFieldWithDesc from '../../../components/options/TextFieldWithDesc';
import CheckboxWithDesc from '../../../components/options/CheckboxWithDesc';
import SelectWithDesc from '../../../components/options/SelectWithDesc';
const initialValues = { const initialValues = {
splitSeparatorType: 'symbol' as SplitOperatorType, splitSeparatorType: 'symbol' as SplitOperatorType,
@@ -38,8 +40,7 @@ const splitOperators: {
export default function SplitText() { export default function SplitText() {
const [input, setInput] = useState<string>(''); const [input, setInput] = useState<string>('');
const [result, setResult] = useState<string>(''); const [result, setResult] = useState<string>('');
// const formRef = useRef<FormikProps<typeof initialValues>>(null); const compute = (optionsValues: typeof initialValues, input: any) => {
const computeExternal = (optionsValues: typeof initialValues, input: any) => {
const { const {
splitSeparatorType, splitSeparatorType,
joinSeparator, joinSeparator,
@@ -80,7 +81,7 @@ export default function SplitText() {
result={<ToolTextResult title={'Sorted list'} value={result} />} result={<ToolTextResult title={'Sorted list'} value={result} />}
/> />
<ToolOptions <ToolOptions
compute={computeExternal} compute={compute}
getGroups={({ values, updateField }) => [ getGroups={({ values, updateField }) => [
{ {
title: 'Input item separator', title: 'Input item separator',
@@ -105,7 +106,59 @@ export default function SplitText() {
}, },
{ {
title: 'Sort method', title: 'Sort method',
component: <Box></Box> component: (
<Box>
<SelectWithDesc
selected={values.sortingMethod}
options={[
{ label: 'Sort Alphabetically', value: 'alphabetic' },
{ label: 'Sort Numerically', value: 'numeric' },
{ label: 'Sort by Length', value: 'length' }
]}
onChange={(value) => updateField('sortingMethod', value)}
description={'Select a sorting method.'}
/>
<SelectWithDesc
selected={values.increasing}
options={[
{ label: 'Increasing order', value: true },
{ label: 'Decreasing order', value: false }
]}
onChange={(value) => {
updateField('increasing', value);
}}
description={'Select a sorting order.'}
/>
<CheckboxWithDesc
title={'Case Sensitive Sort'}
description={
'Sort uppercase and lowercase items separately. Capital letters precede lowercase letters in an ascending list. (Works only in alphabetical sorting mode.)'
}
checked={values.caseSensitive}
onChange={(val) => updateField('caseSensitive', val)}
/>
</Box>
)
},
{
title: 'Sorted item properties',
component: (
<Box>
<TextFieldWithDesc
description={
'Use this symbol as a joiner between items in a sorted list.'
}
value={values.joinSeparator}
onOwnChange={(val) => updateField('joinSeparator', val)}
/>
<CheckboxWithDesc
title={'Remove duplicates'}
description={'Delete duplicate list items.'}
checked={values.removeDuplicated}
onChange={(val) => updateField('removeDuplicated', val)}
/>
</Box>
)
} }
]} ]}
initialValues={initialValues} initialValues={initialValues}

View File

@@ -6,3 +6,13 @@ export function capitalizeFirstLetter(string: string | undefined) {
export function isNumber(number: any) { export function isNumber(number: any) {
return !isNaN(parseFloat(number)) && isFinite(number); return !isNaN(parseFloat(number)) && isFinite(number);
} }
export const replaceSpecialCharacters = (str: string) => {
return str
.replace(/\\n/g, '\n')
.replace(/\\t/g, '\t')
.replace(/\\r/g, '\r')
.replace(/\\b/g, '\b')
.replace(/\\f/g, '\f')
.replace(/\\v/g, '\v');
};