MarkdownToImage.jsx 11.5 KB
Newer Older
fisherdaddy's avatar
fisherdaddy committed
1
import React, { useState, useRef, useEffect } from 'react';
fisherdaddy's avatar
fisherdaddy committed
2
import styled from 'styled-components';
3
import { marked } from 'marked';
4
import { useTranslation } from '../js/i18n';
5
import SEO from './SEO';
6
import DOMPurify from 'dompurify';
fisherdaddy's avatar
fisherdaddy committed
7 8
import { usePageLoading } from '../hooks/usePageLoading';
import LoadingOverlay from './LoadingOverlay';
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

// 更新预设模板
const templates = [
  { 
    name: 'simple',
    bgColor: '#ffffff',
    textColor: '#333333',
    font: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
    padding: '40px'
  },
  {
    name: 'ai-style',
    bgColor: 'linear-gradient(135deg, #6366F1 0%, #4F46E5 100%)',
    textColor: '#ffffff',
    font: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
    padding: '40px'
  },
  {
    name: 'dark',
    bgColor: '#2d3748',
    textColor: '#ffffff',
    font: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
    padding: '40px'
  },
  {
    name: 'paper',
    bgColor: '#fdf6e3',
    textColor: '#333333',
    font: 'Georgia, "Nimbus Roman No9 L", "Songti SC", serif',
    padding: '40px'
  },
  {
    name: 'minimal',
    bgColor: '#f8f9fa',
    textColor: '#1a1a1a',
    font: '-apple-system, "SF Pro Text", sans-serif',
    padding: '40px'
  },
  {
    name: 'tech',
    bgColor: 'linear-gradient(135deg, #0f172a 0%, #1e293b 100%)',
    textColor: '#e2e8f0',
    font: '"SF Mono", SFMono-Regular, Consolas, monospace',
    padding: '40px'
  }
];

const Container = styled.div`
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7ff 0%, #ffffff 100%);
59
  padding: 4rem 2rem 2rem;
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: 
      linear-gradient(90deg, rgba(99, 102, 241, 0.05) 1px, transparent 1px),
      linear-gradient(rgba(99, 102, 241, 0.05) 1px, transparent 1px);
    background-size: 20px 20px;
    pointer-events: none;
  }
`;

const ContentWrapper = styled.div`
  display: flex;
  gap: 2rem;
  max-width: 1400px;
  margin: 0 auto;
  position: relative;
  z-index: 1;

  @media (max-width: 768px) {
    flex-direction: column;
  }
`;

const InputContainer = styled.div`
  flex: 1;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 1.5rem;
  box-shadow: 0 8px 32px rgba(99, 102, 241, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  flex-direction: column;
  gap: 1rem;
`;

const TitleLabel = styled.h2`
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
  background: linear-gradient(135deg, #6366F1 0%, #4F46E5 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: 700;
  letter-spacing: -0.02em;
`;

const Section = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
`;

119 120 121 122 123 124 125 126 127 128
const TemplateSection = styled(Section)`
  margin-bottom: 1rem;
`;

const EditorSection = styled(Section)`
  flex: 1;
  display: flex;
  flex-direction: column;
`;

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
const Label = styled.label`
  font-size: 1rem;
  color: #333333;
`;

const TemplateGrid = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
`;

const TemplateItem = styled.button`
  padding: 0.5rem 1rem;
  background: ${props => props.selected ? 
    'linear-gradient(135deg, #6366F1 0%, #4F46E5 100%)' : 
    'rgba(255, 255, 255, 0.8)'
  };
  color: ${props => props.selected ? '#ffffff' : '#333333'};
  border: 2px solid ${props => props.selected ? '#4F46E5' : 'rgba(99, 102, 241, 0.1)'};
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(99, 102, 241, 0.15);
    border-color: rgba(99, 102, 241, 0.3);
  }

  ${props => props.selected && `
    &::after {
      content: '✓';
      position: absolute;
      top: 4px;
      right: 4px;
      font-size: 12px;
      color: #ffffff;
    }
  `}
`;

173
const Editor = styled.textarea`
174
  width: 100%;
175 176 177 178 179 180 181
  height: 500px;
  padding: 1rem;
  border: none;
  background: transparent;
  font-family: 'SF Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
182
  resize: vertical;
183 184 185 186 187 188 189 190 191 192
  color: #1a1a1a;
  overflow-y: auto;

  &:focus {
    outline: none;
  }

  &::placeholder {
    color: #64748b;
  }
193
`;
fisherdaddy's avatar
fisherdaddy committed
194 195

const DownloadButton = styled.button`
196
  background: linear-gradient(135deg, #6366F1 0%, #4F46E5 100%);
fisherdaddy's avatar
fisherdaddy committed
197
  color: white;
198
  padding: 0.5rem 1rem;
fisherdaddy's avatar
fisherdaddy committed
199
  border: none;
200
  border-radius: 6px;
fisherdaddy's avatar
fisherdaddy committed
201
  cursor: pointer;
202 203 204 205 206 207 208 209
  font-weight: 600;
  transition: opacity 0.2s;
  font-size: 0.9rem;
  position: absolute;
  top: 1.5rem;
  right: 1.5rem;
  opacity: ${props => props.visible ? 1 : 0};
  pointer-events: ${props => props.visible ? 'auto' : 'none'};
fisherdaddy's avatar
fisherdaddy committed
210 211

  &:hover {
212
    opacity: 0.9;
fisherdaddy's avatar
fisherdaddy committed
213 214 215
  }
`;

216 217 218 219 220
const PreviewContainer = styled(InputContainer)`
  overflow: auto;
  position: relative;
  min-height: 400px;
  display: block;
221
  
222 223 224 225 226
  img {
    max-width: 100%;
    height: auto;
    display: block;
    margin: 1em auto;
227
  }
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

  h1, h2, h3, h4, h5, h6 {
    margin-top: 1.5em;
    margin-bottom: 0.5em;
    font-weight: 600;
    line-height: 1.3;
  }

  p {
    margin: 1em 0;
    line-height: 1.6;
  }

  ul, ol {
    margin: 1em 0;
    padding-left: 2em;
  }

  ul {
    list-style-type: disc;
  }

  ol {
    list-style-type: decimal;
  }

  li {
    margin: 0.5em 0;
    line-height: 1.6;
  }

  pre, code {
    background: rgba(0, 0, 0, 0.05);
    border-radius: 4px;
    padding: 0.2em 0.4em;
    font-family: 'SF Mono', monospace;
  }

  pre code {
    background: none;
    padding: 0;
  }

  blockquote {
    border-left: 4px solid #e2e8f0;
    margin: 1em 0;
    padding-left: 1em;
    color: #64748b;
  }

  table {
    border-collapse: collapse;
280
    width: 100%;
281 282 283 284 285 286 287 288 289 290 291
    margin: 1em 0;
  }

  th, td {
    border: 1px solid #e2e8f0;
    padding: 0.5em;
    text-align: left;
  }

  th {
    background: rgba(0, 0, 0, 0.05);
292 293 294 295
  }
`;

const Preview = styled.div`
296 297 298 299 300 301 302 303
  font-family: ${(props) => props.$font || '-apple-system, system-ui, sans-serif'};
  font-size: 16px;
  line-height: 1.6;
  color: ${(props) => props.$color || '#1a1a1a'};
  background: ${(props) => props.$background || '#ffffff'};
  padding: ${(props) => props.$padding || '40px'};
  border-radius: 8px;
  overflow-wrap: break-word;
304
  word-wrap: break-word;
305
  hyphens: auto;
306 307
`;

fisherdaddy's avatar
fisherdaddy committed
308
function MarkdownToImage() {
309
  const { t } = useTranslation();
fisherdaddy's avatar
fisherdaddy committed
310
  const [text, setText] = useState('');
311
  const [selectedTemplate, setSelectedTemplate] = useState(templates[0]);
fisherdaddy's avatar
fisherdaddy committed
312
  const previewRef = useRef(null);
fisherdaddy's avatar
fisherdaddy committed
313
  const isLoading = usePageLoading();
fisherdaddy's avatar
fisherdaddy committed
314 315

  const formatText = (text) => {
316 317
    return marked.parse(text, {
      breaks: true,
318 319 320 321 322 323 324 325 326 327 328 329 330
      gfm: true,
      headerIds: false,
      mangle: false,
      // 自定义图片渲染
      renderer: {
        image(href, title, text) {
          // 处理相对路径
          if (href.startsWith('/')) {
            href = window.location.origin + href;
          }
          return `<img src="${href}" alt="${text}" title="${title || ''}" style="max-width: 100%; height: auto;" crossorigin="anonymous" />`;
        }
      }
331
    });
fisherdaddy's avatar
fisherdaddy committed
332 333 334
  };

  const handleDownload = async () => {
335 336 337
    const previewElement = previewRef.current;
    if (!previewElement) return;

fisherdaddy's avatar
fisherdaddy committed
338
    try {
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
      // 等待图片加载
      const waitForImages = () => {
        const images = previewElement.getElementsByTagName('img');
        const promises = Array.from(images).map(img => {
          if (img.complete) return Promise.resolve();
          return new Promise((resolve, reject) => {
            img.onload = resolve;
            img.onerror = reject;
            // 确保图片使用完整的 URL
            if (img.src.startsWith('/')) {
              img.src = window.location.origin + img.src;
            }
            // 添加跨域属性
            img.crossOrigin = 'anonymous';
          });
        });
        return Promise.all(promises);
      };

      await waitForImages();
      // 等待渲染完成
      await new Promise(resolve => setTimeout(resolve, 500));

fisherdaddy's avatar
fisherdaddy committed
362
      const html2canvas = (await import('html2canvas')).default;
363 364
      const canvas = await html2canvas(previewElement, {
        backgroundColor: selectedTemplate.bgColor,
fisherdaddy's avatar
fisherdaddy committed
365
        scale: 2,
366 367 368 369 370 371 372 373 374 375 376 377 378
        useCORS: true,
        allowTaint: false,
        logging: false,
        onclone: (clonedDoc) => {
          const clonedElement = clonedDoc.querySelector('.markdown-content');
          if (clonedElement) {
            clonedElement.style.width = '100%';
            clonedElement.style.position = 'relative';
            clonedElement.style.transform = 'none';
            clonedElement.style.transformOrigin = '0 0';
            clonedElement.style.overflow = 'visible';
          }
        }
fisherdaddy's avatar
fisherdaddy committed
379 380 381
      });

      const link = document.createElement('a');
382
      link.download = 'markdown-preview.png';
fisherdaddy's avatar
fisherdaddy committed
383 384 385
      link.href = canvas.toDataURL('image/png');
      link.click();
    } catch (error) {
386
      console.error('导出图片失败:', error);
fisherdaddy's avatar
fisherdaddy committed
387 388 389
    }
  };

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
  const renderPreview = () => {
    // 配置 marked 选项
    marked.setOptions({
      gfm: true, // 启用 GitHub 风格的 Markdown
      breaks: true, // 启用换行符转换为 <br>
      headerIds: true,
      mangle: false,
      pedantic: false,
      smartLists: true, // 优化列表输出
      smartypants: true, // 优化标点符号
    });

    // 使用 DOMPurify 清理 HTML
    const cleanHtml = DOMPurify.sanitize(marked(text), {
      ADD_TAGS: ['img'],
      ADD_ATTR: ['src', 'alt'],
    });

    return (
      <div
        ref={previewRef}
        dangerouslySetInnerHTML={{ __html: cleanHtml }}
        style={{
          fontFamily: selectedTemplate.font,
          color: selectedTemplate.textColor,
          background: selectedTemplate.bgColor,
          padding: selectedTemplate.padding,
          minHeight: '100%',
        }}
      />
    );
  };

fisherdaddy's avatar
fisherdaddy committed
423
  return (
fisherdaddy's avatar
fisherdaddy committed
424
    <>
fisherdaddy's avatar
fisherdaddy committed
425
      {isLoading && <LoadingOverlay />}
fisherdaddy's avatar
fisherdaddy committed
426
      <SEO
427 428
        title={t('tools.markdown2image.title')}
        description={t('tools.markdown2image.description')}
fisherdaddy's avatar
fisherdaddy committed
429
      />
430 431 432 433
      <Container>
        
        <ContentWrapper>
          <InputContainer>
434
            <TitleLabel>{t('tools.markdown2image.title')}</TitleLabel>
435 436
            
            {/* 模板选择 */}
437
            <TemplateSection>
438
              <Label>{t('tools.markdown2image.selectTemplate')}</Label>
439 440 441 442 443 444 445 446 447
              <TemplateGrid>
                {templates.map(template => (
                  <TemplateItem
                    key={template.name}
                    selected={template === selectedTemplate}
                    onClick={() => setSelectedTemplate(template)}
                    background={template.bgColor}
                    color={template.textColor}
                  >
448
                    {t(`tools.markdown2image.templates.${template.name}`)}
449 450 451
                  </TemplateItem>
                ))}
              </TemplateGrid>
452
            </TemplateSection>
453 454

            {/* Markdown 编辑器 */}
455
            <EditorSection>
456
              <Label>{t('tools.markdown2image.inputLabel')}</Label>
457
              <Editor
458 459
                value={text}
                onChange={(e) => setText(e.target.value)}
460
                placeholder={t('tools.markdown2image.placeholder')}
461
              />
462
            </EditorSection>
463 464
          </InputContainer>

465 466 467 468
          <PreviewContainer>
            <DownloadButton 
              onClick={handleDownload}
              visible={text.length > 0}
469
            >
470 471 472
              {t('tools.markdown2image.downloadButton')}
            </DownloadButton>
            {renderPreview()}
fisherdaddy's avatar
fisherdaddy committed
473
          </PreviewContainer>
474 475
        </ContentWrapper>
      </Container>
fisherdaddy's avatar
fisherdaddy committed
476
    </>
fisherdaddy's avatar
fisherdaddy committed
477 478 479
  );
}

fisherdaddy's avatar
fisherdaddy committed
480
export default MarkdownToImage;