main

mattermost/focalboard

Last updated at: 28/12/2023 01:42

index.tsx

TLDR

This file defines a React component called H1 that represents a heading. It includes a display component and an input component for rendering the heading and capturing user input, respectively.

Classes

H1

Represents a heading component. It has the following properties:

  • name: The name of the component.
  • displayName: The display name of the component.
  • slashCommand: The slash command associated with the component.
  • prefix: The prefix applied to the heading text.
  • runSlashCommand: A function to execute the slash command associated with the component.
  • editable: A boolean indicating whether the heading is editable.
  • Display: A component responsible for rendering the heading.
  • Input: A component responsible for capturing user input for the heading.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import React, {useRef, useEffect} from 'react'
import {marked} from 'marked'

import {BlockInputProps, ContentType} from '../types'

import './h1.scss'

const H1: ContentType = {
    name: 'h1',
    displayName: 'Title',
    slashCommand: '/title',
    prefix: '# ',
    runSlashCommand: (): void => {},
    editable: true,
    Display: (props: BlockInputProps) => {
        const renderer = new marked.Renderer()
        const html = marked('# ' + props.value, {renderer, breaks: true})
        return (
            <div
                dangerouslySetInnerHTML={{__html: html.trim()}}
            />
        )
    },
    Input: (props: BlockInputProps) => {
        const ref = useRef<HTMLInputElement|null>(null)
        useEffect(() => {
            ref.current?.focus()
        }, [])
        return (
            <input
                ref={ref}
                className='H1'
                data-testid='h1'
                onChange={(e) => props.onChange(e.currentTarget.value)}
                onKeyDown={(e) => {
                    if (props.value === '' && e.key === 'Backspace') {
                        props.onCancel()
                    }
                    if (e.key === 'Enter') {
                        props.onSave(props.value)
                    }
                }}
                value={props.value}
            />
        )
    },
}

H1.runSlashCommand = (changeType: (contentType: ContentType) => void, changeValue: (value: string) => void, ...args: string[]): void => {
    changeType(H1)
    changeValue(args.join(' '))
}

export default H1