Skip to content

Commit

Permalink
fix(dcellar-web-ui): calculate string length in bytes instead of char…
Browse files Browse the repository at this point in the history
…acters
  • Loading branch information
devinxl committed Apr 2, 2024
1 parent 3f7af84 commit 70518d0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
16 changes: 10 additions & 6 deletions apps/dcellar-web-ui/src/components/common/ManageTags/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
} from '@node-real/uikit';
import { memo, useState } from 'react';
import { DCButton } from '../DCButton';
import { countBytes } from '@/utils/coder';

export const DEFAULT_TAG = { key: '', value: '' };

Expand All @@ -26,12 +27,15 @@ interface ManageTagsProps {
export const ManageTags = memo<ManageTagsProps>(function ManageTags({ onSave, onCancel, tags }) {
const [internalTags, setInternalTags] = useState(tags);

const isInvalid = (type: string, value: string) => {
if (type === 'key' && value.length > 32) {
return 'Should not exceed 32 characters.';
}
if (type === 'value' && value.length > 64) {
return 'Should not exceed 64 characters.';
const isInvalid = (type: 'key' | 'value', value: string): string | false => {
const bytesLength = countBytes(value);
const limits: { [key: string]: number } = {
key: 32,
value: 64,
};

if (bytesLength > limits[type]) {
return `Should not exceed ${limits[type]} bytes.`;
}

return false;
Expand Down
6 changes: 6 additions & 0 deletions apps/dcellar-web-ui/src/utils/coder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,9 @@ export function decodeBase64(data: string): Uint8Array {

return bytes;
}

export function countBytes(str: string) {
const encoder = new TextEncoder();
const bytes = encoder.encode(str);
return bytes.length;
}

0 comments on commit 70518d0

Please sign in to comment.