import { useState, useRef } from 'react';
import { action } from '@storybook/addon-actions';
import { Button, Card, CardContent, CardFooter, Flex, Link, Text, TextArea } from '@pega/cosmos-react-core';
import { Editor } from '@pega/cosmos-react-rte';
import { createPegaCustomElement, mockUploadAttachment } from './Editor.mocks';
export default {
    title: 'RTE/Editor',
    component: Editor
};
export const EditorDemo = (args) => {
    const editorRef = useRef(null);
    const onImageAdded = async (image, id) => {
        const src = URL.createObjectURL(image);
        try {
            await mockUploadAttachment(image, e => {
                editorRef.current?.updateAttachmentAttributes(id, (e.loaded * 100) / e.total);
            });
            editorRef.current?.appendImage({
                src,
                alt: image.name,
                attachmentId: 'sample-id'
            }, id);
        }
        catch (error) {
            if (error instanceof Error) {
                editorRef.current?.updateAttachmentAttributes(id, undefined, error.message);
            }
        }
    };
    return (<Editor ref={editorRef} label={args.label} labelHidden={args.labelHidden} info={args.info} status={args.status} required={args.required} disabled={args.disabled} readOnly={args.readOnly} toolbar={['inline-styling', 'lists', 'indentation', 'images', 'links']} onFocus={action('Editor focused')} onBlur={action('Editor blurred')} onChange={action('Editor changed')} onImageAdded={onImageAdded} defaultValue='<body><p>Hi mom <a href="https://google.com">link</a></p><img alt="Example alt text" src="http://via.placeholder.com/640x360"/></body>' additionalInfo={args.showAdditionalInfo
            ? {
                content: (<Flex container={{ direction: 'column', alignItems: 'start', gap: 2 }}>
                  <p>
                    Lorem ipsum dolor sit amet, consectetur it, sed do tempor incididunt ut labore
                    magna aliqua. Nibh praesent tristique magna sit amet. Nec tincidunt praesent
                    semper feugiat nibh sed pulvinar proin gravida.
                  </p>
                  <p>
                    Pharetra pharetra massa massa ultricies mi quis hendrerit dolor. Est velit
                    egestas dui id ornare arcu odio ut. Varius sit amet mattis vulputate enim nulla
                    aliquet porttitor lacus.
                  </p>
                  <Link href='/' target='_blank'>
                    Neque vitae
                  </Link>
                </Flex>)
            }
            : undefined}/>);
};
EditorDemo.args = {
    showAdditionalInfo: false,
    label: 'Form field label',
    labelHidden: false,
    info: 'Enter some value',
    status: undefined,
    required: false,
    disabled: false,
    readOnly: false
};
EditorDemo.argTypes = {
    showAdditionalInfo: { control: { type: 'boolean' } },
    label: { control: { type: 'text' } },
    labelHidden: { control: { type: 'boolean' } },
    info: { control: { type: 'text', label: 'Helper text' } },
    status: {
        options: [undefined, 'success', 'warning', 'error', 'pending'],
        control: { type: 'select' }
    },
    required: { control: { type: 'boolean' } },
    disabled: { control: { type: 'boolean' } },
    readOnly: { control: { type: 'boolean' } }
};
export const EmptyEditorDemo = () => {
    const editorRef = useRef(null);
    const onImageAdded = (image, id) => {
        const src = URL.createObjectURL(image);
        editorRef.current?.appendImage({ src, alt: image.name }, id);
    };
    return (<Editor ref={editorRef} label='Form field label' toolbar={['inline-styling', 'lists', 'indentation', 'images', 'links']} onImageAdded={onImageAdded} onFocus={action('Editor has focus')} onBlur={action('Editor has blurred')} placeholder='Type some stuff in here'/>);
};
export const ReadonlyFormField = () => {
    return (<Editor label='Form field label' readOnly defaultValue={`<article class="main-page-content" lang="en-US"><h1>HTML: HyperText Markup Language</h1><div><p><strong>HTML</strong> (HyperText Markup Language) is the most basic building block of the Web. It defines the meaning and structure of web content. Other technologies besides HTML are generally used to describe a web page's appearance/presentation (<a href="/en-US/docs/Web/CSS">CSS</a>) or functionality/behavior (<a href="/en-US/docs/Web/JavaScript">JavaScript</a>).</p>
      <p>"Hypertext" refers to links that connect web pages to one another, either within a single website or between websites. Links are a fundamental aspect of the Web. By uploading content to the Internet and linking it to pages created by other people, you become an active participant in the World Wide Web.</p>
      <p>HTML uses "markup" to annotate text, images, and other content for display in a Web browser. HTML markup includes special "elements" such as <a href="/en-US/docs/Web/HTML/Element/head"><code>&lt;head&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/title"><code>&lt;title&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/body"><code>&lt;body&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/header"><code>&lt;header&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/footer"><code>&lt;footer&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/article"><code>&lt;article&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/section"><code>&lt;section&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/p"><code>&lt;p&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/div"><code>&lt;div&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/span"><code>&lt;span&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/img"><code>&lt;img&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/aside"><code>&lt;aside&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/audio"><code>&lt;audio&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/canvas"><code>&lt;canvas&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/datalist"><code>&lt;datalist&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/details"><code>&lt;details&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/embed"><code>&lt;embed&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/nav"><code>&lt;nav&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/output"><code>&lt;output&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/progress"><code>&lt;progress&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/video"><code>&lt;video&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/ul"><code>&lt;ul&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/ol"><code>&lt;ol&gt;</code></a>, <a href="/en-US/docs/Web/HTML/Element/li"><code>&lt;li&gt;</code></a> and many others.</p>
      <p>An HTML element is set off from other text in a document by "tags", which consist of the element name surrounded by "<code>&lt;</code>" and "<code>&gt;</code>".&nbsp; The name of an element inside a tag is case insensitive. That is, it can be written in uppercase, lowercase, or a mixture. For example, the <code>&lt;title&gt;</code> tag can be written as <code>&lt;Title&gt;</code>, <code>&lt;TITLE&gt;</code>, or in any other way.</p>

      <div id="on-github" class="on-github"><h3>Found a problem with this page?</h3><ul><li><a href="https://github.com/mdn/content/edit/main/files/en-us/web/html/index.md" title="You're going to need to sign in to GitHub first (Opens in a new tab)" target="_blank" rel="noopener noreferrer">Edit on <b>GitHub</b></a></li><li><a href="https://github.com/mdn/content/blob/main/files/en-us/web/html/index.md" title="Folder: en-us/web/html (Opens in a new tab)" target="_blank" rel="noopener noreferrer">Source on <b>GitHub</b></a></li><li><a href="https://github.com/mdn/content/issues/new?body=MDN+URL%3A+https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FHTML%0A%0A%23%23%23%23+What+information+was+incorrect%2C+unhelpful%2C+or+incomplete%3F%0A%0A%0A%23%23%23%23+Specific+section+or+headline%3F%0A%0A%0A%23%23%23%23+What+did+you+expect+to+see%3F%0A%0A%0A%23%23%23%23+Did+you+test+this%3F+If+so%2C+how%3F%0A%0A%0A%3C%21--+Do+not+make+changes+below+this+line+--%3E%0A%3Cdetails%3E%0A%3Csummary%3EMDN+Content+page+report+details%3C%2Fsummary%3E%0A%0A*+Folder%3A+%60en-us%2Fweb%2Fhtml%60%0A*+MDN+URL%3A+https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FHTML%0A*+GitHub+URL%3A+https%3A%2F%2Fgithub.com%2Fmdn%2Fcontent%2Fblob%2Fmain%2Ffiles%2Fen-us%2Fweb%2Fhtml%2Findex.md%0A*+Last+commit%3A+https%3A%2F%2Fgithub.com%2Fmdn%2Fcontent%2Fcommit%2F775662998e66813a612e3ff27e02f2ada867bc17%0A*+Document+last+modified%3A+2021-10-03T00%3A01%3A51.000Z%0A%0A%3C%2Fdetails%3E&amp;title=Issue+with+%22HTML%3A+HyperText+Markup+Language%22%3A+%28short+summary+here+please%29&amp;labels=needs-triage%2CContent%3AHTML" title="This will take you to https://github.com/mdn/content to file a new issue" target="_blank" rel="noopener noreferrer">Report a problem with this content on <b>GitHub</b></a></li><li>Want to fix the problem yourself? See <a href="https://github.com/mdn/content/blob/main/README.md" target="_blank" rel="noopener noreferrer">our Contribution guide</a>.</li></ul></div>
      `}/>);
};
export const InitOptionsEditorDemo = () => {
    const editorRef = useRef(null);
    const onImageAdded = (image, id) => {
        const src = URL.createObjectURL(image);
        editorRef.current?.appendImage({ src, alt: image.name }, id);
    };
    return (<Flex container={{ direction: 'column', gap: 2 }}>
      <Editor ref={editorRef} label='Editor with initOptions' defaultValue='<p></p>' onImageAdded={onImageAdded} initOptions={{
            pasteDataImages: false,
            textPatterns: false,
            initInstanceCallback: editor => {
                editor.shortcuts.add('meta+b', '', () => { });
            }
        }}/>
      <Flex container={{ gap: 1 }}>
        <Button onClick={() => {
            const clipboardData = new DataTransfer();
            clipboardData.setData('text/html', '<img src="https://www.pega.com/themes/custom/pegawww_theme/images/pega-logo.svg" alt="Pega" />');
            const clipboardEvent = new ClipboardEvent('paste', {
                clipboardData
            });
            editorRef.current?.getEditor()?.dispatch('paste', clipboardEvent);
        }}>
          Paste image
        </Button>
      </Flex>
    </Flex>);
};
export const CustomComponentDemo = () => {
    const editorRef = useRef(null);
    const [editor, setEditor] = useState({});
    const onCustomAction = () => {
        editor.insertContent('<pega-custom>Inserted from toolbar</pega-custom>');
    };
    return (<Editor ref={editorRef} label='Form field label' toolbar={['inline-styling', 'lists', 'indentation', 'links', 'images']} defaultValue='<body><p>Hi mom <a href="https://google.com">link</a></p><p>hi <pega-custom>Hello from custom element.</pega-custom></p></body>' customComponents={[{ createCustomElement: createPegaCustomElement, name: 'pega-custom' }]} customActions={[
            {
                icon: 'pega',
                text: 'Insert a custom element',
                onMouseDown: () => {
                    onCustomAction();
                }
            }
        ]} onInit={initializedEditor => {
            setEditor(initializedEditor);
        }}/>);
};
export const RichTextEditorWithLogs = () => {
    const editorRef = useRef(null);
    const [content, setContent] = useState();
    const onImageAdded = (image, id) => {
        const src = URL.createObjectURL(image);
        editorRef.current?.appendImage({ src, alt: image.name }, id);
    };
    const showContent = (type) => {
        if (type === 'html')
            setContent(editorRef.current?.getHtml());
        else if (type === 'plain_text')
            setContent(editorRef.current?.getPlainText());
        else if (type === 'rich_text')
            setContent(editorRef.current?.getRichText());
    };
    return (<Flex container={{ direction: 'column', gap: 2 }}>
      <Editor ref={editorRef} toolbar={['inline-styling', 'headers', 'tables', 'links', 'images', 'lists', 'indentation']} onImageAdded={onImageAdded} label='Rich text editor with logs' info='Click on the buttons below to show the different formatted outputs of the RTE'/>

      <Flex container={{ gap: 1 }}>
        <Button onClick={() => editorRef.current?.focus()}>Focus</Button>
        <Button onClick={() => showContent('html')}>Show HTML</Button>
        <Button onClick={() => showContent('plain_text')}>Show plain text</Button>
        <Button onClick={() => showContent('rich_text')}>Show rich text</Button>
        <Button onClick={() => editorRef.current?.insertText('Some text')}>Insert text</Button>
        <Button onClick={() => editorRef.current?.clear()}>Clear</Button>
        <Button onClick={() => {
            const clipboardData = new DataTransfer();
            clipboardData.setData('text/html', '<img src="https://www.pega.com/themes/custom/pegawww_theme/images/pega-logo.svg" alt="Pega" />');
            const clipboardEvent = new ClipboardEvent('paste', {
                clipboardData
            });
            editorRef.current?.getEditor()?.dispatch('paste', clipboardEvent);
        }}>
          Paste image
        </Button>
      </Flex>

      <Text data-testid='textRegion'>{content}</Text>
    </Flex>);
};
export const RichTextEditorHtmlParsingDemo = () => {
    const [html, setHtml] = useState('<p>Hello world!</p>');
    const rteRef = useRef(null);
    const onImageAdded = (image, id) => {
        const src = URL.createObjectURL(image);
        rteRef.current?.appendImage({ src, alt: image.name }, id);
    };
    return (<Flex container={{ direction: 'column', gap: 2 }}>
      <Card>
        <CardContent>
          <TextArea value={html} onChange={e => setHtml(e.target.value)}/>
        </CardContent>
        <CardFooter>
          <Button onClick={() => rteRef.current?.insertHtml(html.trim(), true)}>
            Overwrite RTE with new HTML
          </Button>
        </CardFooter>
      </Card>
      <Editor defaultValue={html} onImageAdded={onImageAdded} ref={rteRef} label='Form field label' toolbar={['inline-styling', 'headers', 'tables', 'links', 'images', 'lists', 'indentation']}/>
    </Flex>);
};
export const ReorderableEditor = () => {
    const [flip, setFlip] = useState(true);
    return (<>
      <Button onClick={() => setFlip(!flip)}>Toggle</Button>
      {[
            <Editor key={flip ? 'a' : 'b'} label={`Editor ${flip ? 'A' : 'B'}`} defaultValue={`<p>Editor ${flip ? 'A' : 'B'} content</p>`}/>,
            <Editor key={flip ? 'b' : 'a'} label={`Editor ${flip ? 'B' : 'A'}`} defaultValue={`<p>Editor ${flip ? 'B' : 'A'} content</p>`}/>
        ]}
    </>);
};
//# sourceMappingURL=Editor.stories.jsx.map