diff --git a/packages/typography/.eslintrc.cjs b/packages/typography/.eslintrc.cjs new file mode 100644 index 0000000..8ca3407 --- /dev/null +++ b/packages/typography/.eslintrc.cjs @@ -0,0 +1,7 @@ +module.exports = { + root: true, + extends: [require.resolve('@nzyme/eslint/typescript')], + parserOptions: { + project: `${__dirname}/tsconfig.json`, + }, +}; diff --git a/packages/typography/package.json b/packages/typography/package.json new file mode 100644 index 0000000..7df6709 --- /dev/null +++ b/packages/typography/package.json @@ -0,0 +1,20 @@ +{ + "name": "@nzyme/typography", + "version": "1.0.0", + "type": "module", + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "sideEffects": false, + "repository": "https://github.com/nzymejs/nzyme.git", + "author": "Michał Kędrzyński ", + "private": true, + "scripts": { + "eslint": "eslint . --fix --cache", + "build": "tsc --build" + }, + "dependencies": { + "@nzyme/types": "*", + "@nzyme/utils": "*" + } +} diff --git a/packages/typography/src/fixOrphans.ts b/packages/typography/src/fixOrphans.ts new file mode 100644 index 0000000..09036d8 --- /dev/null +++ b/packages/typography/src/fixOrphans.ts @@ -0,0 +1,25 @@ +const spaceAfterShortWordRegex = /([\s(]|^)(\w{1,2})\s/gmu; +const longWordRegex = /\s([^\s]{12,})/gmu; + +/** + * Search for any word, that is 3 or less characters long + * Such short words should not end up on the end of the line. + * We add non-breakable space at the end of the word. + * Source: https://boanastudio.com/blog/text-in-responsive-web-design + * @param text Text to fix + */ +export function fixOrphans(text: string) { + // use [^\s] to match anything but whitespace characters + return ( + text + .replace(spaceAfterShortWordRegex, (search, whitespace: string, word: string) => { + // replace spaces between short words with a non-breakable space + // do not swap it with any other character! + return whitespace + word + '\xa0'; + }) + // roll back the operation if following word has 12 or more letters + .replace(longWordRegex, (search, group: string) => { + return ' ' + group; + }) + ); +} diff --git a/packages/typography/src/index.ts b/packages/typography/src/index.ts new file mode 100644 index 0000000..c8b94ff --- /dev/null +++ b/packages/typography/src/index.ts @@ -0,0 +1 @@ +export * from './fixOrphans.js'; diff --git a/packages/typography/tsconfig.json b/packages/typography/tsconfig.json new file mode 100644 index 0000000..d73550a --- /dev/null +++ b/packages/typography/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "tsBuildInfoFile": "./dist/.tsbuildinfo", + "rootDir": "./src" + }, + "include": ["src/**/*.ts", "src/**/*.json"], + "references": [ + { + "path": "../types/tsconfig.json" + }, + { + "path": "../utils/tsconfig.json" + } + ] +}