aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/components/scaling_input.tsx
blob: c31de1fb5bc41ae499b30e557d2436caec60dd74 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import { ObjectMap } from '@0x/types';
import * as _ from 'lodash';
import * as React from 'react';

import { ColorOption } from '../style/theme';
import { util } from '../util/util';

import { Input } from './ui/input';

export enum ScalingInputPhase {
    FixedFontSize,
    ScalingFontSize,
}

export interface ScalingSettings {
    percentageToReduceFontSizePerCharacter: number;
    // 1ch = the width of the 0 chararacter.
    // Allow to customize 'char' length for different characters.
    characterWidthOverrides: ObjectMap<number>;
    // How much room to leave to the right of the scaling input.
    additionalInputSpaceInCh: number;
}

export interface ScalingInputProps {
    type?: string;
    textLengthThreshold: number;
    maxFontSizePx: number;
    value: string;
    emptyInputWidthCh: number;
    onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
    onFontSizeChange: (fontSizePx: number) => void;
    fontColor?: ColorOption;
    placeholder?: string;
    maxLength?: number;
    scalingSettings: ScalingSettings;
    isDisabled: boolean;
    hasAutofocus: boolean;
}

export interface ScalingInputSnapshot {
    inputWidthPx: number;
}

// These are magic numbers that were determined experimentally.
const defaultScalingSettings: ScalingSettings = {
    percentageToReduceFontSizePerCharacter: 0.1,
    characterWidthOverrides: {
        '1': 0.7,
        '.': 0.4,
    },
    additionalInputSpaceInCh: 0.4,
};

export class ScalingInput extends React.PureComponent<ScalingInputProps> {
    public static defaultProps = {
        onChange: util.boundNoop,
        onFontSizeChange: util.boundNoop,
        maxLength: 9,
        scalingSettings: defaultScalingSettings,
        isDisabled: false,
        hasAutofocus: false,
    };
    private readonly _inputRef = React.createRef<HTMLInputElement>();
    public static getPhase(textLengthThreshold: number, value: string): ScalingInputPhase {
        if (value.length <= textLengthThreshold) {
            return ScalingInputPhase.FixedFontSize;
        }
        return ScalingInputPhase.ScalingFontSize;
    }
    public static getPhaseFromProps(props: ScalingInputProps): ScalingInputPhase {
        const { value, textLengthThreshold } = props;
        return ScalingInput.getPhase(textLengthThreshold, value);
    }
    public static calculateFontSize(
        textLengthThreshold: number,
        maxFontSizePx: number,
        phase: ScalingInputPhase,
        value: string,
        percentageToReduceFontSizePerCharacter: number,
    ): number {
        if (phase !== ScalingInputPhase.ScalingFontSize) {
            return maxFontSizePx;
        }
        const charactersOverMax = value.length - textLengthThreshold;
        const scalingFactor = (1 - percentageToReduceFontSizePerCharacter) ** charactersOverMax;
        const fontSize = scalingFactor * maxFontSizePx;
        return fontSize;
    }
    public static calculateFontSizeFromProps(props: ScalingInputProps, phase: ScalingInputPhase): number {
        const { textLengthThreshold, value, maxFontSizePx, scalingSettings } = props;
        return ScalingInput.calculateFontSize(
            textLengthThreshold,
            maxFontSizePx,
            phase,
            value,
            scalingSettings.percentageToReduceFontSizePerCharacter,
        );
    }
    public componentDidMount(): void {
        // Trigger an initial notification of the calculated fontSize.
        const currentPhase = ScalingInput.getPhaseFromProps(this.props);
        const currentFontSize = ScalingInput.calculateFontSizeFromProps(this.props, currentPhase);
        this.props.onFontSizeChange(currentFontSize);
    }
    public componentDidUpdate(prevProps: ScalingInputProps): void {
        const prevPhase = ScalingInput.getPhaseFromProps(prevProps);
        const curPhase = ScalingInput.getPhaseFromProps(this.props);
        const prevFontSize = ScalingInput.calculateFontSizeFromProps(prevProps, prevPhase);
        const curFontSize = ScalingInput.calculateFontSizeFromProps(this.props, curPhase);
        // If font size has changed, notify.
        if (prevFontSize !== curFontSize) {
            this.props.onFontSizeChange(curFontSize);
        }
    }
    public render(): React.ReactNode {
        const { type, hasAutofocus, isDisabled, fontColor, placeholder, value, maxLength } = this.props;
        const phase = ScalingInput.getPhaseFromProps(this.props);
        return (
            <Input
                type={type}
                ref={this._inputRef as any}
                fontColor={fontColor}
                onChange={this._handleChange}
                value={value}
                placeholder={placeholder}
                fontSize={`${this._calculateFontSize(phase)}px`}
                width={this._calculateWidth(phase)}
                maxLength={maxLength}
                disabled={isDisabled}
                autoFocus={hasAutofocus}
            />
        );
    }
    private readonly _calculateWidth = (phase: ScalingInputPhase): string => {
        const { value, scalingSettings } = this.props;
        if (_.isEmpty(value)) {
            return `${this.props.emptyInputWidthCh}ch`;
        }
        const lengthInCh = _.reduce(
            value.split(''),
            (sum, char) => {
                const widthOverride = scalingSettings.characterWidthOverrides[char];
                if (!_.isUndefined(widthOverride)) {
                    // tslint is confused
                    // tslint:disable-next-line:restrict-plus-operands
                    return sum + widthOverride;
                }
                return sum + 1;
            },
            scalingSettings.additionalInputSpaceInCh,
        );
        return `${lengthInCh}ch`;
    };
    private readonly _calculateFontSize = (phase: ScalingInputPhase): number => {
        return ScalingInput.calculateFontSizeFromProps(this.props, phase);
    };
    private readonly _handleChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
        const value = event.target.value;
        const { maxLength } = this.props;
        if (!_.isUndefined(value) && !_.isUndefined(maxLength) && value.length > maxLength) {
            return;
        }
        this.props.onChange(event);
    };
}