aiWritingContent.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. function stripCodeFences(content) {
  2. return String(content || '')
  3. .replace(/```(?:html)?\s*/gi, '')
  4. .replace(/```/g, '')
  5. .trim()
  6. }
  7. function escapeHtml(content) {
  8. return String(content || '')
  9. .replace(/&/g, '&')
  10. .replace(/</g, '&lt;')
  11. .replace(/>/g, '&gt;')
  12. .replace(/"/g, '&quot;')
  13. .replace(/'/g, '&#39;')
  14. }
  15. function plainTextToHtml(content) {
  16. return String(content || '')
  17. .split(/\n{2,}/)
  18. .map(part => part.trim())
  19. .filter(Boolean)
  20. .map(part => `<p>${escapeHtml(part).replace(/\n/g, '<br>')}</p>`)
  21. .join('')
  22. }
  23. export function prepareAIWritingEditorHtml(content) {
  24. let html = stripCodeFences(content)
  25. if (!html) return ''
  26. const bodyMatch = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i)
  27. if (bodyMatch) {
  28. html = bodyMatch[1].trim()
  29. }
  30. const firstContentTag = html.search(/<(article|section|main|div|h[1-6]|p|table|ul|ol)\b/i)
  31. if (firstContentTag > 0 && html.slice(0, firstContentTag).trim()) {
  32. html = html.slice(firstContentTag)
  33. }
  34. html = html
  35. .replace(/<!DOCTYPE[^>]*>/gi, '')
  36. .replace(/<html[^>]*>/gi, '')
  37. .replace(/<\/html>/gi, '')
  38. .replace(/<head[^>]*>[\s\S]*?<\/head>/gi, '')
  39. .replace(/<body[^>]*>/gi, '')
  40. .replace(/<\/body>/gi, '')
  41. .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
  42. .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
  43. .replace(/<meta[^>]*>/gi, '')
  44. .replace(/<title[^>]*>[\s\S]*?<\/title>/gi, '')
  45. .trim()
  46. if (!/<[^>]+>/.test(html)) {
  47. return plainTextToHtml(html)
  48. }
  49. return html
  50. }