From 94e47678082159a695026fd80b0a4cff6718964f Mon Sep 17 00:00:00 2001 From: Michael Fix Date: Thu, 16 Nov 2017 19:01:38 -0800 Subject: [PATCH] Debounce language changes (#141) - Closes #140 --- components/Carbon.js | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/components/Carbon.js b/components/Carbon.js index 147d94e..7b6f9da 100644 --- a/components/Carbon.js +++ b/components/Carbon.js @@ -4,6 +4,8 @@ import React from 'react' import domtoimage from 'dom-to-image' import Spinner from 'react-spinner' import toHash from 'tohash' +import debounce from 'lodash.debounce' +import ms from 'ms' import WindowControls from '../components/WindowControls' import CodeMirror from '../lib/react-codemirror' import { @@ -55,22 +57,26 @@ class Carbon extends React.Component { this.props.updateCode(newCode) } - handleLanguageChange(newCode, config) { - const props = (config && config.customProps) || this.props - - if (props.config.language === 'auto') { - // try to set the language - const detectedLanguage = hljs.highlightAuto(newCode).language - const languageMode = - LANGUAGE_MODE_HASH[detectedLanguage] || LANGUAGE_NAME_HASH[detectedLanguage] - - if (languageMode) { - this.setState({ language: languageMode.mime || languageMode.mode }) + handleLanguageChange = debounce( + (newCode, config) => { + const props = (config && config.customProps) || this.props + + if (props.config.language === 'auto') { + // try to set the language + const detectedLanguage = hljs.highlightAuto(newCode).language + const languageMode = + LANGUAGE_MODE_HASH[detectedLanguage] || LANGUAGE_NAME_HASH[detectedLanguage] + + if (languageMode) { + this.setState({ language: languageMode.mime || languageMode.mode }) + } + } else { + this.setState({ language: props.config.language }) } - } else { - this.setState({ language: props.config.language }) - } - } + }, + ms('300ms'), + { trailing: true } + ) render() { const config = { ...DEFAULT_SETTINGS, ...this.props.config }