WechatFormatter.jsx 9.72 KB
Newer Older
1 2 3 4 5 6 7 8 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 59 60 61 62 63 64 65 66 67 68 69
import React, { useState, useRef } from 'react';
import { marked } from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
import styled from 'styled-components';
import SEO from './SEO';
import { useTranslation } from '../js/i18n';

// 配置 marked 使用 highlight.js
marked.setOptions({
  highlight: function(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(code, { language: lang }).value;
    }
    return hljs.highlightAuto(code).value;
  },
  langPrefix: 'hljs language-',
});

// 容器样式
const Container = styled.div`
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7ff 0%, #ffffff 100%);
  padding: 4rem 2rem 2rem;
  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 EditorContainer = 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);
`;

const PreviewContainer = styled(EditorContainer)`
  overflow: auto;
  position: relative;
`;

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
const PreviewHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
`;

const FloatingCopyButton = styled.button`
  background: linear-gradient(135deg, #6366F1 0%, #4F46E5 100%);
  color: white;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.2s;
  font-size: 0.9rem;
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
  z-index: 100;
  opacity: ${props => props.visible ? 1 : 0};
  pointer-events: ${props => props.visible ? 'auto' : 'none'};
  transform: ${props => props.visible ? 'scale(1)' : 'scale(0.9)'};

  &:hover {
    opacity: 0.9;
    transform: scale(1.05);
  }
`;

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
const Editor = styled.textarea`
  width: 100%;
  min-height: 400px;
  padding: 1rem;
  border: none;
  background: transparent;
  font-family: 'SF Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
  color: #1a1a1a;

  &:focus {
    outline: none;
  }
`;

const Preview = styled.div`
  font-family: -apple-system, system-ui, sans-serif;
  color: #1a1a1a;
  line-height: 1.6;

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

  p {
    margin: 1em 0;
  }

  img {
    max-width: 100%;
    height: auto;
  }

  table {
    border-collapse: collapse;
    width: 100%;
    margin: 1em 0;
  }

  th, td {
    border: 1px solid rgba(99, 102, 241, 0.2);
    padding: 0.5em;
  }
`;

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 CopyButton = styled.button`
  background: linear-gradient(135deg, #6366F1 0%, #4F46E5 100%);
  color: white;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  transition: opacity 0.2s;
  font-size: 0.9rem;
  opacity: ${props => props.visible ? 1 : 0};
  pointer-events: ${props => props.visible ? 'auto' : 'none'};

  &:hover {
    opacity: 0.9;
  }
`;

const FormatSelector = styled.div`
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
`;

const RadioLabel = styled.label`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  font-weight: 500;
  color: #4b5563;
  transition: color 0.2s;

  &:hover {
    color: #1f2937;
  }

  input {
    accent-color: #6366F1;
  }
`;

const WechatFormatter = () => {
  const [input, setInput] = useState('');
  const [output, setOutput] = useState('');
  const [format, setFormat] = useState('markdown'); // 'markdown' 或 'html'
  const tempDivRef = useRef(null);
208
  const previewContainerRef = useRef(null);
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
  const { t } = useTranslation();

  const handleInputChange = (e) => {
    setInput(e.target.value);
    convertToWechat(e.target.value, format);
  };

  const handleFormatChange = (e) => {
    setFormat(e.target.value);
    convertToWechat(input, e.target.value);
  };

  const convertToWechat = (text, format) => {
    let html = '';
    if (format === 'markdown') {
      html = marked(text);
    } else {
      html = text;
    }

229
    // 处理标题,使用微信公众号兼容的样式
230 231 232 233 234 235
    html = html.replace(/<h1>(.*?)<\/h1>/g, '<section><span><span textstyle style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 24px;">\$1</span></span></section>');
    html = html.replace(/<h2>(.*?)<\/h2>/g, '<section><span><span textstyle style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 22px;">\$1</span></span></section>');
    html = html.replace(/<h3>(.*?)<\/h3>/g, '<section><span><span textstyle style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 20px;">\$1</span></span></section>');
    html = html.replace(/<h4>(.*?)<\/h4>/g, '<section><span><span textstyle style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 18px;">\$1</span></span></section>');
    html = html.replace(/<h5>(.*?)<\/h5>/g, '<section><span><span textstyle style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 16px;">\$1</span></span></section>');
    html = html.replace(/<h6>(.*?)<\/h6>/g, '<section><span><span textstyle style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 16px;">\$1</span></span></section>');
236 237 238 239 240 241 242 243

    // 处理列表中的粗体文本后跟冒号的情况
    html = html.replace(/<li><strong>(.*?)<\/strong>:(.*?)<\/li>/g, 
      '<li><span style="display: inline; white-space: nowrap;"><strong>\$1</strong>:</span>\$2</li>');
    
    // 确保列表项中的内容保持在一行
    html = html.replace(/<li>(.*?)<\/li>/g, 
      '<li style="margin-bottom: 0.5em; line-height: 1.6;">\$1</li>');
244 245 246 247
      
    // 为ul或ol中的最后一个li添加额外的标签
    html = html.replace(/(<\/li>)(?=\s*<\/[uo]l>)/g, 
      '<section><span leaf=""><br class="ProseMirror-trailingBreak"></span></section></li>');
248

249
    // 添加微信公众号特定的样式
250
    var wechatHtml = `
251 252
      <div class="wechat-content prose max-w-none">
        ${html}
253
      <div>
254
    `;
255 256

    console.log('wechatHtml>>>', wechatHtml);
257 258 259 260 261 262
    setOutput(wechatHtml);
  };

  const copyToClipboard = () => {
    // 创建一个临时的 div 元素来存放内容
    if (!tempDivRef.current) {
263
      console.log('444>>>');
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
      tempDivRef.current = document.createElement('div');
      document.body.appendChild(tempDivRef.current);
    }

    // 将 HTML 内容添加到临时 div
    tempDivRef.current.innerHTML = output;
    tempDivRef.current.style.position = 'absolute';
    tempDivRef.current.style.left = '-9999px';

    // 创建一个范围来选择内容
    const range = document.createRange();
    range.selectNode(tempDivRef.current);

    // 清除当前选择
    window.getSelection().removeAllRanges();
    
    // 选择内容
    window.getSelection().addRange(range);

    try {
      // 执行复制命令
      document.execCommand('copy');
      alert('已复制到剪贴板!现在可以直接粘贴到微信公众号编辑器中。');
    } catch (err) {
      console.error('复制失败:', err);
      alert('复制失败,请手动复制。');
    }

    // 清理
    window.getSelection().removeAllRanges();
  };

  return (
    <>
      <SEO
        title="微信公众号排版工具"
        description="将 Markdown 或 HTML 转换为微信公众号优质排版"
      />
      <Container>
        <ContentWrapper>
          <EditorContainer>
            <TitleLabel>公众号排版编辑器</TitleLabel>
            <FormatSelector>
              <RadioLabel>
                <input
                  type="radio"
                  value="markdown"
                  checked={format === 'markdown'}
                  onChange={handleFormatChange}
                />
                Markdown
              </RadioLabel>
              <RadioLabel>
                <input
                  type="radio"
                  value="html"
                  checked={format === 'html'}
                  onChange={handleFormatChange}
                />
                HTML
              </RadioLabel>
            </FormatSelector>
            <Editor
              value={input}
              onChange={handleInputChange}
              placeholder={`请输入${format === 'markdown' ? 'Markdown' : 'HTML'}内容...`}
            />
          </EditorContainer>
332 333 334 335
          <PreviewContainer ref={previewContainerRef}>
            <PreviewHeader>
              <TitleLabel style={{ margin: 0 }}>预览效果</TitleLabel>
            </PreviewHeader>
336 337 338 339 340 341
            <Preview 
              className="preview-content"
              dangerouslySetInnerHTML={{ __html: output }} 
            />
          </PreviewContainer>
        </ContentWrapper>
342 343 344 345 346 347
        <FloatingCopyButton 
          onClick={copyToClipboard}
          visible={output.length > 0}
        >
          复制内容
        </FloatingCopyButton>
348 349 350 351 352 353
      </Container>
    </>
  );
};

export default WechatFormatter;