Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor #5

Merged
merged 3 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Test

on:
push:
branches: ['main']
pull_request:
branches: ['main']

jobs:
test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- uses: denoland/setup-deno@v1
with:
deno-version: v1.x

- name: Lint
run: |
deno task lint

- name: Test
run: |
deno test
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"deno.enable": true,
"deno.lint": true,
"editor.formatOnSave": true,
"editor.defaultFormatter": "denoland.vscode-deno"
}
2 changes: 1 addition & 1 deletion deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "@krutoo/input-mask",
"version": "0.0.0",
"tasks": {
"lint": "deno lint && deno check src/**/*.ts",
"lint": "deno check src/**/*.ts && deno lint && deno fmt --check",
"build-npm": "deno run -A scripts/build-npm.ts"
},
"imports": {
Expand Down
3 changes: 3 additions & 0 deletions example/rsbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,8 @@ export default defineConfig({
polyfill: "off",
assetPrefix: "/input-mask/",
},
html: {
title: "Example of @krutoo/input-mask",
},
plugins: [pluginReact()],
});
6 changes: 3 additions & 3 deletions example/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { InputHTMLAttributes, useEffect, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { type InputMaskControl, InputMask } from "../../src/dom/mod";
import { type InputMask, createInputMask } from "@krutoo/input-mask/dom";
import "./index.css";

const variants = [
Expand Down Expand Up @@ -44,11 +44,11 @@ function DemoBlock({
label: string;
inputProps?: InputHTMLAttributes<HTMLInputElement>;
}) {
const [inputMask, setInputMask] = useState<InputMaskControl | null>(null);
const [inputMask, setInputMask] = useState<InputMask | null>(null);
const ref = useRef<HTMLInputElement>(null);

useEffect(() => {
const im = InputMask(ref.current!, { mask });
const im = createInputMask(ref.current!, { mask });

setInputMask(im);

Expand Down
4 changes: 4 additions & 0 deletions example/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"paths": {
"@krutoo/input-mask/core": ["../src/core/mod.ts"],
"@krutoo/input-mask/dom": ["../src/dom/mod.ts"]
}
},
"exclude": ["node_modules"]
}
50 changes: 25 additions & 25 deletions src/core/__test__/changes.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { describe, test } from '@std/testing/bdd';
import { expect } from '@std/expect';
import { defineChanges } from '../changes.ts';
import { Range } from '../range.ts';
import { RangeUtil } from '../range.ts';

describe('defineChanges()', () => {
describe('insert cases', () => {
test('insertion to empty field', () => {
const prev = { value: '', range: Range.of(0) };
const next = { value: 'text', range: Range.of(4, 4) };
const prev = { value: '', range: RangeUtil.of(0) };
const next = { value: 'text', range: RangeUtil.of(4, 4) };

const result = defineChanges(prev, next);

Expand All @@ -20,8 +20,8 @@ describe('defineChanges()', () => {
});

test('insertion to end of non empty field', () => {
const prev = { value: 'foo', range: Range.of(3) };
const next = { value: 'foobar', range: Range.of(6, 6) };
const prev = { value: 'foo', range: RangeUtil.of(3) };
const next = { value: 'foobar', range: RangeUtil.of(6, 6) };

const result = defineChanges(prev, next);

Expand All @@ -34,8 +34,8 @@ describe('defineChanges()', () => {
});

test('insertion to start of non empty field', () => {
const prev = { value: 'foo', range: Range.of(0) };
const next = { value: 'barfoo', range: Range.of(3, 3) };
const prev = { value: 'foo', range: RangeUtil.of(0) };
const next = { value: 'barfoo', range: RangeUtil.of(3, 3) };

const result = defineChanges(prev, next);

Expand All @@ -48,8 +48,8 @@ describe('defineChanges()', () => {
});

test('insertion to middle of non empty field', () => {
const prev = { value: 'foobaz', range: Range.of(3) };
const next = { value: 'foobarbaz', range: Range.of(6, 6) };
const prev = { value: 'foobaz', range: RangeUtil.of(3) };
const next = { value: 'foobarbaz', range: RangeUtil.of(6, 6) };

const result = defineChanges(prev, next);

Expand All @@ -65,8 +65,8 @@ describe('defineChanges()', () => {
describe('delete cases', () => {
describe('delete backward cases', () => {
test('delete from end: soft', () => {
const prev = { value: 'text', range: Range.of(4) };
const next = { value: 'tex', range: Range.of(3) };
const prev = { value: 'text', range: RangeUtil.of(4) };
const next = { value: 'tex', range: RangeUtil.of(3) };

const result = defineChanges(prev, next);

Expand All @@ -79,8 +79,8 @@ describe('defineChanges()', () => {
});

test('delete from end: hard', () => {
const prev = { value: 'text', range: Range.of(4) };
const next = { value: '', range: Range.of(0) };
const prev = { value: 'text', range: RangeUtil.of(4) };
const next = { value: '', range: RangeUtil.of(0) };

const result = defineChanges(prev, next);

Expand All @@ -93,8 +93,8 @@ describe('defineChanges()', () => {
});

test('delete from middle: soft', () => {
const prev = { value: 'abcdef', range: Range.of(4) };
const next = { value: 'abcef', range: Range.of(3) };
const prev = { value: 'abcdef', range: RangeUtil.of(4) };
const next = { value: 'abcef', range: RangeUtil.of(3) };

const result = defineChanges(prev, next);

Expand All @@ -107,8 +107,8 @@ describe('defineChanges()', () => {
});

test('delete from middle: hard', () => {
const prev = { value: 'abcdef', range: Range.of(4) };
const next = { value: 'ef', range: Range.of(0) };
const prev = { value: 'abcdef', range: RangeUtil.of(4) };
const next = { value: 'ef', range: RangeUtil.of(0) };

const result = defineChanges(prev, next);

Expand All @@ -123,8 +123,8 @@ describe('defineChanges()', () => {

describe('delete forward cases', () => {
test('delete from start: soft', () => {
const prev = { value: 'abcdef', range: Range.of(0) };
const next = { value: 'bcdef', range: Range.of(0) };
const prev = { value: 'abcdef', range: RangeUtil.of(0) };
const next = { value: 'bcdef', range: RangeUtil.of(0) };

const result = defineChanges(prev, next);

Expand All @@ -137,8 +137,8 @@ describe('defineChanges()', () => {
});

test('delete from start: hard', () => {
const prev = { value: 'abcdef', range: Range.of(0) };
const next = { value: '', range: Range.of(0) };
const prev = { value: 'abcdef', range: RangeUtil.of(0) };
const next = { value: '', range: RangeUtil.of(0) };

const result = defineChanges(prev, next);

Expand All @@ -151,8 +151,8 @@ describe('defineChanges()', () => {
});

test('delete from middle: soft', () => {
const prev = { value: 'abcdef', range: Range.of(3) };
const next = { value: 'abcef', range: Range.of(3) };
const prev = { value: 'abcdef', range: RangeUtil.of(3) };
const next = { value: 'abcef', range: RangeUtil.of(3) };

const result = defineChanges(prev, next);

Expand All @@ -165,8 +165,8 @@ describe('defineChanges()', () => {
});

test('delete from middle: hard', () => {
const prev = { value: 'abcdef', range: Range.of(3) };
const next = { value: 'abc', range: Range.of(3) };
const prev = { value: 'abcdef', range: RangeUtil.of(3) };
const next = { value: 'abc', range: RangeUtil.of(3) };

const result = defineChanges(prev, next);

Expand Down
32 changes: 16 additions & 16 deletions src/core/changes.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Range } from './range.ts';
import type { ChangeAction, InputState } from './reducer.ts';
import type { ChangeAction, InputState } from './types.ts';
import { RangeUtil } from './range.ts';

/**
* Получив предыдущее и новое состояния текстового поля определит тип изменений.
* ВАЖНО: только определяет изменения, ничего не знает про маски.
*/
export const defineChanges = (prev: InputState, next: InputState): ChangeAction => {
export function defineChanges(prev: InputState, next: InputState): ChangeAction {
const hasChanges = prev.value !== next.value;

let type: ChangeAction['type'] = 'UNKNOWN';
Expand All @@ -14,7 +14,7 @@ export const defineChanges = (prev: InputState, next: InputState): ChangeAction
// define type
if (hasChanges) {
if (next.value.length > prev.value.length) {
if (Range.size(prev.range) > 0) {
if (RangeUtil.size(prev.range) > 0) {
type = 'REPLACE';
} else {
type = 'INSERT';
Expand All @@ -26,14 +26,14 @@ export const defineChanges = (prev: InputState, next: InputState): ChangeAction

if (
restored === prev.value ||
(Range.size(prev.range) === 0 && Range.size(next.range) === 0)
(RangeUtil.size(prev.range) === 0 && RangeUtil.size(next.range) === 0)
) {
type = 'DELETE';
} else {
type = 'REPLACE';
}
}
} else if (!Range.equals(prev.range, next.range)) {
} else if (!RangeUtil.equals(prev.range, next.range)) {
// вставили то же самое что уже было введено
type = 'REPLACE';
}
Expand All @@ -44,27 +44,27 @@ export const defineChanges = (prev: InputState, next: InputState): ChangeAction
payload = {
...next,
insertPosition: prev.range.start,
insertIndices: Range.spreadOf(prev.range.start, next.range.end),
insertIndices: RangeUtil.spreadOf(prev.range.start, next.range.end),
};
break;

case 'DELETE': {
let deleteIndices: number[] = [];

if (Range.size(prev.range) === 0) {
if (RangeUtil.size(prev.range) === 0) {
// удалили какую-то часть текста (delete forward/backward, hard/soft...)
if (next.range.start === prev.range.start) {
// удалили после каретки (aka delete)
const delta = prev.value.length - next.value.length;

deleteIndices = Range.spreadOf(prev.range.start, prev.range.start + delta);
deleteIndices = RangeUtil.spreadOf(prev.range.start, prev.range.start + delta);
} else {
// удалили перед кареткой (aka backspace)
deleteIndices = Range.spreadOf(next.range.start, prev.range.start);
deleteIndices = RangeUtil.spreadOf(next.range.start, prev.range.start);
}
} else {
// просто вырезали выделенную часть
deleteIndices = Range.spreadOf(prev.range.start, prev.range.end);
deleteIndices = RangeUtil.spreadOf(prev.range.start, prev.range.end);
}

payload = {
Expand All @@ -81,16 +81,16 @@ export const defineChanges = (prev: InputState, next: InputState): ChangeAction
payload = {
...next,
replacePosition: prev.range.start,
deleteIndices: Range.spread(prev.range),
insertIndices: Range.spreadOf(prev.range.start, next.range.end),
deleteIndices: RangeUtil.spread(prev.range),
insertIndices: RangeUtil.spreadOf(prev.range.start, next.range.end),
};
} else {
// вставили то же самое что уже было введено
payload = {
...next,
replacePosition: prev.range.start,
deleteIndices: Range.spread(prev.range),
insertIndices: Range.spread(prev.range),
deleteIndices: RangeUtil.spread(prev.range),
insertIndices: RangeUtil.spread(prev.range),
};
}
break;
Expand All @@ -101,4 +101,4 @@ export const defineChanges = (prev: InputState, next: InputState): ChangeAction
}

return { type, payload } as ChangeAction;
};
}
7 changes: 4 additions & 3 deletions src/core/mod.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './range.ts';
export * from './changes.ts';
export * from './reducer.ts';
export type * from './types.ts';
export { RangeUtil } from './range.ts';
export { defineChanges } from './changes.ts';
export { createReducer } from './reducer.ts';
47 changes: 25 additions & 22 deletions src/core/range.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,42 @@
export interface IRange {
start: number;
end: number;

/** @deprecated Use "start" instead. */
head: number;

/** @deprecated Use "end" instead. */
last: number;
}
import type { Range } from './types.ts';

/**
* Работа с числовыми диапазонами.
*/
export const Range = {
of: (start: number, end = start): IRange => ({ start, end, head: start, last: end }),
export abstract class RangeUtil {
static of(start: number, end = start): Range {
return { start, end };
}

clone: (r: IRange): IRange => ({ ...r }),
static clone(range: Range): Range {
return { ...range };
}

map: (r: IRange, cb: (n: number) => number): IRange => Range.of(cb(r.start), cb(r.end)),
static map(range: Range, callback: (n: number) => number): Range {
return RangeUtil.of(callback(range.start), callback(range.end));
}

equals: (a: IRange, b: IRange): boolean => a.start === b.start && a.end === b.end,
static equals(a: Range, b: Range): boolean {
return a.start === b.start && a.end === b.end;
}

size: (r: IRange) => Math.max(r.start, r.end) - Math.min(r.start, r.end),
static size(range: Range): number {
return Math.max(range.start, range.end) - Math.min(range.start, range.end);
}

spread: (r: IRange): number[] => {
static spread(range: Range): number[] {
const result = [];

if (r.start !== r.end) {
for (let i = r.start; i < r.end; i++) {
if (range.start !== range.end) {
for (let i = range.start; i < range.end; i++) {
result.push(i);
}
}

return result;
},
}

spreadOf: (start: number, end: number): number[] => Range.spread(Range.of(start, end)),
};
static spreadOf(start: number, end: number): number[] {
return RangeUtil.spread(RangeUtil.of(start, end));
}
}
Loading