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 KeyCombo component #2256

Merged
merged 1 commit into from
Mar 16, 2018
Merged
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
63 changes: 34 additions & 29 deletions packages/core/src/components/hotkeys/keyCombo.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/**
/*
* Copyright 2016 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the terms of the LICENSE file distributed with this project.
Expand All @@ -25,38 +25,43 @@ const KeyIcons: { [key: string]: IconName } = {
};

export interface IKeyComboProps extends IProps {
allowInInput?: boolean;
/** The key combo to display, such as `"cmd + s"`. */
combo: string;
disabled?: boolean;
preventDefault?: boolean;
stopPropagation?: boolean;

/**
* Whether to render in a minimal style.
* If `false`, each key in the combo will be rendered inside a `kbd.pt-key`.
* If `true`, only the icon or short name of a key will be rendered with no wrapper styles.
* @default false
*/
minimal?: boolean;
}

export class KeyCombo extends React.Component<IKeyComboProps, {}> {
public render() {
const keys = normalizeKeyCombo(this.props.combo);
const components = [] as JSX.Element[];
const rootClasses = classNames("pt-key-combo", this.props.className);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
const icon = KeyIcons[key];
if (icon != null) {
components.push(
<kbd className="pt-key pt-modifier-key" key={`key-${i}`}>
<Icon icon={icon} /> {key}
</kbd>,
);
} else {
if (key.length === 1) {
key = key.toUpperCase();
}
components.push(
<kbd className="pt-key" key={`key-${i}`}>
{key}
</kbd>,
);
}
}
return <span className={rootClasses}>{components}</span>;
const { className, combo, minimal } = this.props;
const keys = normalizeKeyCombo(combo)
.map(key => (key.length === 1 ? key.toUpperCase() : key))
.map(minimal ? this.renderMinimalKey : this.renderKey);
return <span className={classNames("pt-key-combo", className)}>{keys}</span>;
}

private renderKey = (key: string, index: number) => {
const icon = KeyIcons[key];
const reactKey = `key-${index}`;
return icon == null ? (
<kbd className="pt-key" key={reactKey}>
{key}
</kbd>
) : (
<kbd className="pt-key pt-modifier-key" key={reactKey}>
<Icon icon={icon} /> {key}
</kbd>
);
};

private renderMinimalKey = (key: string, index: number) => {
const icon = KeyIcons[key];
return icon == null ? key : <Icon icon={icon} key={`key-${index}`} />;
};
}