import yaml from 'js-yaml' import hljs from 'highlight.js/lib/common' import defaultSettings from './default-settings' import validateGist from './gist-validator' import { useEffect, useState, useRef } from 'react' import Json from 'shared/components/json-highlight.js' import Popout from 'shared/components/popout.js' const countLines = (txt) => txt.split('\n').length const Edit = (props) => { let { gist, setGist, design } = props const inputRef = useRef(null) const [gistAsYaml, setGistAsYaml] = useState(null) const [numLines, setNumLines] = useState(0) const [error, setError] = useState(null) useEffect(() => { setGistAsYaml(yaml.dump(gist)) }, [gist]) useEffect(() => { if (gistAsYaml) setNumLines(countLines(gistAsYaml)) }, [gistAsYaml]) const onSave = () => { setError(null) const editedAsJson = yaml.load(inputRef.current.value) const validation = validateGist(editedAsJson, design) if (validation.valid) { setGist({ ...defaultSettings, ...editedAsJson, design: gist.design }) } else { const newError = JSON.stringify(validation.errors, null, 2) const newErrorHighlight = hljs.highlight(newError, { language: 'json' }) setError(newError) } } const onKeyUp = (e) => { setNumLines(countLines(e.target.value)) } return (
Your input wasn't saved due to the following errors: