import { Card } from '@automattic/components'; import debug from 'debug'; import PropTypes from 'prop-types'; import { Component } from 'react'; import DocumentHead from 'calypso/components/data/document-head'; import Main from 'calypso/components/main'; import SearchCard from 'calypso/components/search-card'; import DocService from './service'; import './style.scss'; /** * Constants */ const DEFAULT_FILES = [ 'docs/guide/index.md', 'README.md', 'docs/CONTRIBUTING.md', 'docs/coding-guidelines.md', 'docs/coding-guidelines/javascript.md', 'docs/coding-guidelines/css.md', 'docs/coding-guidelines/html.md', 'docs/accessibility.md', ]; /** * Module variables */ const log = debug( 'calypso:devdocs' ); export default class Devdocs extends Component { static displayName = 'Devdocs'; static propTypes = { term: PropTypes.string, }; static defaultProps = { term: '', }; state = { term: this.props.term, results: [], defaultResults: [], inputValue: '', searching: false, }; // load default files if not already cached loadDefaultFiles = () => { if ( this.state.defaultResults.length ) { return; } DocService.list( DEFAULT_FILES, ( err, results ) => { if ( ! err ) { this.setState( { defaultResults: results, } ); } } ); }; componentDidMount() { const { term } = this.state; this.loadDefaultFiles(); if ( ! term ) { return; } this.onSearchChange( this.state.term ); this.onSearch( this.state.term ); } componentDidUpdate( prevProps, prevState ) { if ( typeof this.props.onSearchChange === 'function' && prevState.term !== this.state.term ) { this.props.onSearchChange( this.state.term ); } } notFound = () => { return ( this.state.inputValue && this.state.term && ! this.state.results.length && ! this.state.searching ); }; onSearchChange = ( term ) => { this.setState( { inputValue: term, term: term, searching: !! term, } ); }; onSearch = ( term ) => { if ( ! term ) { return; } DocService.search( term, ( err, results ) => { if ( err ) { log( 'search error: %o', err ); } this.setState( { results, searching: false, } ); } ); }; results = () => { if ( this.notFound() ) { return

Not Found

; } const searchResults = this.state.inputValue ? this.state.results : this.state.defaultResults; return searchResults.map( function ( result ) { let url = '/devdocs/' + result.path; if ( this.state.term ) { url += '?term=' + encodeURIComponent( this.state.term ); } return (

{ result.title }

{ result.path }

{ this.snippet( result ) }
); }, this ); }; snippet = ( result ) => { // split around tags to avoid setting unescaped inner HTML const parts = result.snippet.split( /(.*?<\/mark>)/ ); return (
{ parts.map( function ( part, i ) { const markMatch = part.match( /(.*?)<\/mark>/ ); if ( markMatch ) { return { markMatch[ 1 ] }; } return part; } ) }
); }; render() { return (
{ this.results() }
); } }