Skip to content

Commit

Permalink
refactor regex enhancer; implement edit feature for attachment proper…
Browse files Browse the repository at this point in the history
…ty when variant=default;
  • Loading branch information
anobaka committed Sep 4, 2024
1 parent 8017871 commit 8500e3f
Show file tree
Hide file tree
Showing 8 changed files with 124 additions and 30 deletions.
Original file line number Diff line number Diff line change
@@ -1,40 +1,102 @@
import { useTranslation } from 'react-i18next';
import { DeleteOutlined, FileAddOutlined, LoadingOutlined, UploadOutlined } from '@ant-design/icons';
import { Img } from 'react-image';
import React from 'react';
import type { ValueRendererProps } from '../models';
import serverConfig from '@/serverConfig';
import BApi from '@/sdk/BApi';
import NotSet from '@/components/StandardValue/ValueRenderer/Renderers/components/NotSet';
import CustomIcon from '@/components/CustomIcon';
import { Button, Snippet, Tooltip } from '@/components/bakaui';
import { splitPathIntoSegments } from '@/components/utils';
import { useBakabaseContext } from '@/components/ContextProvider/BakabaseContextProvider';
import FileSystemSelectorDialog from '@/components/FileSystemSelector/Dialog';

type AttachmentValueRendererProps = Omit<ValueRendererProps<string[]>, 'variant'> & {
variant: ValueRendererProps<string[]>['variant'];
};

export default ({ value, variant, editor, ...props }: AttachmentValueRendererProps) => {
const { t } = useTranslation();
const { createPortal } = useBakabaseContext();

const v = variant ?? 'default';

if (!value || value.length == 0) {
return (
<NotSet />
);
}
const editable = !!editor;

switch (v) {
case 'default':
return (
<div className={'flex items-center gap-2 flex-wrap'}>
{value.map(v => {
{value?.map(v => {
const pathSegments = splitPathIntoSegments(v);
return (
<img src={`${serverConfig.apiEndpoint}/tool/thumbnail?path=${encodeURIComponent(v)}`} alt={v} />
<div className={'flex flex-col gap-1 max-w-[100px] relative group'}>
<Img
src={[`${serverConfig.apiEndpoint}/tool/thumbnail?path=${encodeURIComponent(v)}`]}
loader={(
<LoadingOutlined className={'text-2xl'} />
)}
unloader={(
<CustomIcon type={'image-slash'} className={'text-2xl'} />
)}
alt={''}
style={{
maxWidth: 100,
maxHeight: 100,
}}
title={v}
/>
<Button
isIconOnly
color={'danger'}
size={'sm'}
// variant={'light'}
className={'top-0 right-0 absolute hidden group-hover:block'}
style={{ transform: 'translate(50%, -50%)', zIndex: 1 }}
onClick={() => {
const newValue = value.filter(e => e != v);
editor?.onValueChange?.(newValue, newValue);
}}
>
<DeleteOutlined className={'text-lg'} />
</Button>
</div>
);
})}
{editable && (
<div className={'flex items-center justify-center w-[80px] h-[80px]'}>
<Button
isIconOnly
color={'primary'}
variant={'light'}
onClick={() => {
createPortal(FileSystemSelectorDialog, {
targetType: 'file',
onSelected: entry => {
const newValue = (value ?? []).concat([entry.path]);
editor?.onValueChange?.(newValue, newValue);
},
});
}}
>
<FileAddOutlined className={'text-lg'} />
</Button>
</div>
)}
</div>
);
case 'light':
return (
<span>
{(value.join(','))}
</span>
);
if (!value || value.length == 0) {
return (
<NotSet />
);
} else {
return (
<span>
{(value.join(','))}
</span>
);
}
}
};
10 changes: 9 additions & 1 deletion src/ClientApp/src/localization/cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -1368,5 +1368,13 @@
"Be cautions: once you modify the text in one line, it will be treated as a new tag, and the original tag will be deleted.": "请注意:一旦您修改了一行中的文本,它将会被视为一个新的标签,原有的标签将会被删除。",
"{{count}} data will be deleted": "{{count}}条数据将会被删除",
"{{count}} data will be added": "{{count}}条数据将会被添加",
"Tags will be changed": "标签即将变更"
"Tags will be changed": "标签即将变更",
"Regex expressions": "正则表达式",
"Available capture groups:": "有效的捕获组:",
"No named capture groups were found, so the enhancement will not take effect.": "没有发现任何捕获组名称,增强将不会生效。",
"You can set multiple regex expressions to match the file or folder name of each resource.": "您可以设置多个正则表达式作用于资源的文件(夹)名上。",
"Text matched by multiple capture groups with the same name will be merged into a list and deduplicated.":"被具有相同名称的捕获组匹配到的文本将会被合并成一个列表并去重。",
"After setting regex expressions, you must go to category page to configure regex enhancer for each category.":"在设置完正则表达式后,您需要在分类页面配置为分类配置正则表达式增强器。",
"You need to use the same name(index-based group name will be ignored) as the capture group for the dynamic enhancement target, otherwise the resource may not be enhanced.":"您需要在动态增强目标中配置和捕获组一样的名称(数字组名会被忽略),否则资源将不会被增强。",
"Regex enhancer": "正则增强器"
}
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,12 @@ export default ({ applyPatches = () => {} }: {applyPatches: (API: any, patches:
})}
</div>
) : (
<div>{t('No capture groups were found, so the enhancement will not take effect.')}</div>
<div>{t('No named capture groups were found, so the enhancement will not take effect.')}</div>
)}
<div>{t('You can set multiple regex expressions to match the file or folder name of each resource.')}</div>
<div>{t('Text matched by multiple capture groups with the same name will be merged into a list and deduplicated.')}</div>
<div>{t('After setting regex expressions, you must go to category page to configure regex enhancer for each category.')}</div>
<div>{t('You need to use the same name as the capture group for the dynamic enhancement target, otherwise the resource may not be enhanced.')}</div>
<div>{t('You need to use the same name(index-based group name will be ignored) as the capture group for the dynamic enhancement target, otherwise the resource may not be enhanced.')}</div>
</div>
)}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -339,9 +339,25 @@ await _customPropertyService.AddRange(
var valuesToAdd = pvs.Except(valuesToUpdate).ToList();
await _customPropertyValueService.UpdateRange(valuesToUpdate);
await _customPropertyValueService.AddRange(valuesToAdd);
var remainingPvKeys = pvs.Select(p => p.BizKey).ToHashSet();
var valueIdsToDelete = currentPropertyValues.Where(cpv => !remainingPvKeys.Contains(cpv.BizKey))
.Select(cpv => cpv.Id).ToList();

var remainingPvScopeKeys = enhancements
.Select(e => e.EnhancerId)
.ToHashSet()
.Select(x => _enhancerDescriptors.TryGet(x)?.PropertyValueScope ?? -1)
.Where(x => x > 0)
.ToDictionary(d => d, d => pvs.Where(pv => pv.Scope == d).Select(x => x.BizKey));

// var remainingPvScopeKeys = pvs.GroupBy(d => d.Scope)
// .ToDictionary(d => d.Key, d => d.Select(p => p.BizKey).ToHashSet());
var valueIdsToDelete = new List<int>();
foreach (var scopeValues in currentPropertyValues.GroupBy(x => x.Scope))
{
if (remainingPvScopeKeys.TryGetValue(scopeValues.Key, out var bizKeys))
{
valueIdsToDelete.AddRange(scopeValues.Where(x => !bizKeys.Contains(x.BizKey)).Select(v => v.Id));
}
}

await _customPropertyValueService.RemoveByKeys(valueIdsToDelete);

foreach (var (e, v) in enhancementCpvMap)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,22 @@ public class RegexEnhancer(

foreach (var exp in expressions)
{
var match = System.Text.RegularExpressions.Regex.Match(resource.FileName, exp, RegexOptions.IgnoreCase);
var regex = new System.Text.RegularExpressions.Regex(exp, RegexOptions.IgnoreCase);
var match = regex.Match(resource.FileName);
if (match.Success)
{
foreach (var key in match.Groups.Keys)
foreach (var name in regex.GetGroupNames())
{
ctx.CaptureGroupsAndValues ??= [];
if (!ctx.CaptureGroupsAndValues.TryGetValue(key, out var values))
if (!int.TryParse(name, out _))
{
ctx.CaptureGroupsAndValues[key] = values = new List<string>();
}
ctx.CaptureGroupsAndValues ??= [];
if (!ctx.CaptureGroupsAndValues.TryGetValue(name, out var values))
{
ctx.CaptureGroupsAndValues[name] = values = new List<string>();
}

values.Add(match.Groups[key].Value);
values.Add(match.Groups[name].Value);
}
}
}
}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,9 @@
<value>Introduction</value>
</data>
<data name="Enhancer_ExHentai_Description" xml:space="preserve">
<value />
<value>1. You must first set the ExHentai cookie in the system settings.
2. The first resource from the search results will be used as the target resource.
3. You can also specify which tags to exclude.</value>
</data>
<data name="Enhancer_Bangumi_Name" xml:space="preserve">
<value>Bangumi</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,9 +233,8 @@
<data name="Enhancer_DLsite_Target_Rating_Name" xml:space="preserve">
<value>评分</value>
</data>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="Enhancer_Regex_Name" type="System.Resources.ResXNullRef, System.Windows.Forms">
<value />
<data name="Enhancer_Regex_Name" xml:space="preserve">
<value>正则表达式</value>
</data>
<data name="Enhancer_Regex_Target_CaptureGroups_Name" xml:space="preserve">
<value>捕获组</value>
Expand Down

0 comments on commit 8500e3f

Please sign in to comment.