From c017be2a5492575d6a9faef784c8f43077ac2c96 Mon Sep 17 00:00:00 2001 From: "Carlos R. L. Rodrigues" <37986729+carlos-r-l-rodrigues@users.noreply.github.com> Date: Wed, 7 Aug 2024 11:33:19 -0300 Subject: [PATCH] chore(utils): improve to handle util (#8487) --- .../src/common/__tests__/to-handle.spec.ts | 21 +++++++++++++++++-- packages/core/utils/src/common/to-handle.ts | 4 +++- .../core/utils/src/common/validate-handle.ts | 2 -- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/packages/core/utils/src/common/__tests__/to-handle.spec.ts b/packages/core/utils/src/common/__tests__/to-handle.spec.ts index ddc1869247..e5161b4c20 100644 --- a/packages/core/utils/src/common/__tests__/to-handle.spec.ts +++ b/packages/core/utils/src/common/__tests__/to-handle.spec.ts @@ -1,7 +1,8 @@ import { toHandle } from "../to-handle" +import { isValidHandle } from "../validate-handle" describe("normalizeHandle", function () { - it("should generate URL friendly handles", function () { + describe("should generate URL friendly handles", function () { const expectations = [ { input: "The fan boy's club", @@ -22,6 +23,7 @@ describe("normalizeHandle", function () { { input: "-first-product", output: "-first-product", + invalid: true, }, { input: "user.product", @@ -30,15 +32,30 @@ describe("normalizeHandle", function () { { input: "_first-product", output: "-first-product", + invalid: true, }, { input: "_HELLO_WORLD", output: "-hello-world", + invalid: true, + }, + { + input: "title: Hello - World", + output: "title-hello-world", + }, + { + input: "hiphenated - title - __bold__", + output: "hiphenated-title-bold-", + invalid: true, }, ] expectations.forEach((expectation) => { - expect(toHandle(expectation.input)).toEqual(expectation.output) + const handle = toHandle(expectation.input) + it(`should convert "${expectation.input}" to "${expectation.output}"`, () => { + expect(handle).toEqual(expectation.output) + expect(isValidHandle(handle)).toBe(!expectation.invalid) + }) }) }) }) diff --git a/packages/core/utils/src/common/to-handle.ts b/packages/core/utils/src/common/to-handle.ts index 56800cd2c4..915c7aba57 100644 --- a/packages/core/utils/src/common/to-handle.ts +++ b/packages/core/utils/src/common/to-handle.ts @@ -14,5 +14,7 @@ export const toHandle = (value: string): string => { .toLowerCase() .normalize("NFD") .replace(/[\u0300-\u036f]/g, "") - ).replace(/[^a-z0-9A-Z-_]/g, "") + ) + .replace(/[^a-z0-9A-Z-]/g, "") + .replace(/-{2,}/g, "-") } diff --git a/packages/core/utils/src/common/validate-handle.ts b/packages/core/utils/src/common/validate-handle.ts index 01edd607a3..ce513d3e6b 100644 --- a/packages/core/utils/src/common/validate-handle.ts +++ b/packages/core/utils/src/common/validate-handle.ts @@ -1,5 +1,3 @@ -import { kebabCase } from "./to-kebab-case" - /** * Helper method to validate entity "handle" to be URL * friendly.