diff --git a/frontend/app/ConverterClient.js b/frontend/app/ConverterClient.js index ff119ea..089a318 100644 --- a/frontend/app/ConverterClient.js +++ b/frontend/app/ConverterClient.js @@ -29,6 +29,7 @@ const ApiModal = dynamic(() => import('../components/ApiModal'), { ssr: false }) const LegalModal = dynamic(() => import('../components/LegalModal'), { ssr: false }); const RecentSessionsSidebar = dynamic(() => import('../components/RecentSessionsSidebar'), { ssr: false }); const MobileMenu = dynamic(() => import('../components/converter/MobileMenu'), { ssr: false }); +const TipSupportCard = dynamic(() => import('../components/converter/TipSupportCard'), { ssr: false }); export default function ConverterClient({ children }) { const { uiText } = useI18n(); @@ -54,6 +55,7 @@ export default function ConverterClient({ children }) { accept={ACCEPT_ATTRIBUTE} aria-label={uiText("Choose documents to optimize")} className="hidden" + onClick={vm.tip.cancel} onChange={(e) => { if (e.target.files?.length) { converter.addFiles(e.target.files); @@ -167,6 +169,7 @@ export default function ConverterClient({ children }) { {ui.legalModal && } + {vm.tip.pending && !vm.tip.blocked && } ); } diff --git a/frontend/components/LLMiserFooter.js b/frontend/components/LLMiserFooter.js index e1beedc..bf33843 100644 --- a/frontend/components/LLMiserFooter.js +++ b/frontend/components/LLMiserFooter.js @@ -91,6 +91,7 @@ export default function LLMiserFooter({
+
+

{uiText('LLMiser is free and runs on a server I pay for. If it saved you time, a small tip helps keep it online.')}

+
+ dismiss('support')}>{uiText('Support on Ko-fi')} + +
+ + + + ); +} diff --git a/frontend/components/converter/TipSupportCard.module.css b/frontend/components/converter/TipSupportCard.module.css new file mode 100644 index 0000000..608e634 --- /dev/null +++ b/frontend/components/converter/TipSupportCard.module.css @@ -0,0 +1,47 @@ +.card { + position: fixed; + z-index: 44; + right: 1rem; + bottom: calc(1rem + var(--tip-offset, 0px)); + width: min(360px, calc(100vw - 2rem)); + max-height: calc(100dvh - 2rem); + overflow: auto; + border: 1px solid var(--border-3); + border-radius: 16px; + background: var(--surface); + color: var(--text); + box-shadow: 0 12px 36px #0003; + text-align: start; +} + +.content { padding: 12px; animation: arrive 160ms ease-out; } +.banner { display: block; width: 100%; height: auto; border-radius: 10px; } +.heading { display: flex; justify-content: space-between; align-items: center; gap: 4px; } +.heading h2 { font-size: 1.1rem; font-weight: 700; margin: 0; } +.content p { margin: 0 0 12px; font-size: .875rem; line-height: 1.45; } +.actions { display: flex; flex-wrap: wrap; gap: 8px; } +.actions a, .actions button, .close, .already { + min-width: 44px; + min-height: 44px; + display: inline-flex; + align-items: center; + justify-content: center; + padding: 6px 12px; + border-radius: 999px; + font-size: .875rem; + text-decoration: none; + cursor: pointer; +} +.actions a { font-weight: 650; } +.actions button { border: 1px solid var(--border-3); background: var(--surface-2); } +.close { font-size: 1.25rem; } +.already { text-decoration: underline; text-underline-offset: 3px; } +.card :is(a, button):focus-visible { outline: 2px solid var(--text); outline-offset: 2px; } + +@media (max-width: 639px) { + .card { left: 8px; right: 8px; width: auto; bottom: calc(76px + env(safe-area-inset-bottom) + var(--tip-offset, 0px)); max-height: 45dvh; } + .banner { max-height: 88px; object-fit: contain; } +} + +@keyframes arrive { from { transform: translateY(6px); opacity: 0; } to { transform: translateY(0); opacity: 1; } } +@media (prefers-reduced-motion: reduce) { .content { animation: none; } } diff --git a/frontend/lib/i18n/messages/de.json b/frontend/lib/i18n/messages/de.json index 39bf743..757381a 100644 --- a/frontend/lib/i18n/messages/de.json +++ b/frontend/lib/i18n/messages/de.json @@ -238,11 +238,13 @@ "Frequently asked questions": "Häufig gestellte Fragen", "Full formatted document": "Vollständig formatiertes Dokument", "GitHub": "GitHub", + "Glad that worked!": "Schön, dass es geklappt hat!", "Heading-aligned chunks for vector embeddings": "An Überschriften ausgerichtete Abschnitte für Vektoreinbettungen", "How can document preparation reduce LLM costs?": "Wie kann Dokumentenvorbereitung LLM-Kosten senken?", "How can document preparation reduce LLM input costs?": "Wie senkt Dokumentenvorbereitung die LLM-Eingabekosten?", "How do I convert documents with LLMiser?": "Wie konvertiere ich Dokumente mit LLMiser?", "How does LLMiser help optimize LLM costs?": "Wie hilft LLMiser bei der LLM-Kostenoptimierung?", + "I already did": "Schon unterstützt", "If a result download fails, you can use its saved reference to request fresh download links without uploading or converting the file again. This sends the conversion reference to our service. Signed download links are not saved in local storage. Server retrieval stops when its files are deleted. Your cached Markdown copy can still be opened after server deletion.": "Wenn ein Ergebnis nicht heruntergeladen werden kann, können Sie mit dem gespeicherten Verweis neue Downloadlinks anfordern, ohne die Datei erneut hochzuladen oder zu konvertieren. Dabei wird der Konvertierungsverweis an unseren Dienst gesendet. Signierte Downloadlinks werden nicht im lokalen Speicher abgelegt. Nach dem Löschen der Dateien ist kein Serverabruf mehr möglich. Ihre zwischengespeicherte Markdown-Kopie lässt sich weiterhin öffnen.", "If any part of these terms turns out to be invalid, the rest still applies.": "Sollten einzelne Bestimmungen unwirksam sein, bleiben die übrigen gültig.", "If you have a complaint, write to devbehindyou@gmail.com first. We aim to answer within 14 days.": "Bei Beschwerden schreiben Sie zunächst an devbehindyou@gmail.com. Wir streben eine Antwort innerhalb von 14 Tagen an.", @@ -282,6 +284,7 @@ "LLMiser is a free LLM cost optimizer for document inputs. Convert PDFs, Word files, spreadsheets, slides, images and ZIP projects to Markdown, then trim unnecessary context before sending it to an AI assistant or retrieval pipeline.": "LLMiser ist ein kostenloser LLM-Kostenoptimierer für Dokumenteneingaben. Konvertieren Sie PDFs, Word-Dateien, Tabellen, Folien, Bilder und ZIP-Projekte in Markdown und entfernen Sie unnötigen Kontext, bevor Sie ihn an einen KI-Assistenten oder eine Abrufpipeline senden.", "LLMiser is a free service with no guaranteed uptime. We can change, pause or end all or part of it. Where we reasonably can, we'll announce big changes in advance.": "LLMiser ist kostenlos, ohne garantierte Verfügbarkeit. Wir können den Dienst ganz oder teilweise ändern, aussetzen oder beenden. Größere Änderungen kündigen wir soweit zumutbar vorher an.", "LLMiser is busy right now. Please try again shortly.": "LLMiser ist gerade ausgelastet. Bitte in Kürze erneut versuchen.", + "LLMiser is free and runs on a server I pay for. If it saved you time, a small tip helps keep it online.": "LLMiser ist kostenlos und läuft auf einem Server, den ich bezahle. Wenn es Ihnen Zeit gespart hat, hilft ein kleines Trinkgeld, den Dienst online zu halten.", "LLMiser is free. You keep full ownership of your files.": "LLMiser ist kostenlos. Sie behalten alle Eigentumsrechte an Ihren Dateien.", "LLMiser is provided by DevBehindYou. Contact: devbehindyou@gmail.com.": "LLMiser wird von DevBehindYou bereitgestellt. Kontakt: devbehindyou@gmail.com.", "LLMiser is run by DevBehindYou. For anything about your data, write to devbehindyou@gmail.com.": "LLMiser wird von DevBehindYou betrieben. Bei Fragen zu Ihren Daten schreiben Sie an devbehindyou@gmail.com.", @@ -317,6 +320,7 @@ "Markdown with headings, lists and pipe tables": "Markdown mit Überschriften, Listen und Tabellen", "Markdown · UTF-8": "Markdown · UTF-8", "Max 5 sessions stored": "Maximal 5 Konvertierungen gespeichert", + "Maybe later": "Vielleicht später", "Measure the result for your model": "Ergebnis für Ihr Modell messen", "Menu": "Menü", "Minimizes token density": "Reduziert die Tokenanzahl", @@ -462,6 +466,7 @@ "Stored files changed. Refresh and try again.": "Die gespeicherten Dateien haben sich geändert. Aktualisieren Sie die Ansicht und versuchen Sie es erneut.", "Stripped of metadata & extra line breaks": "Ohne Metadaten und zusätzliche Zeilenumbrüche", "Strips metadata & extra lines": "Entfernt Metadaten und zusätzliche Zeilen", + "Support on Ko-fi": "Auf Ko-fi unterstützen", "Supported documents and output": "Unterstützte Dokumente und Ausgabe", "Switch to {v0} mode": "Zum Modus {v0} wechseln", "Task": "Aufgabe", @@ -481,6 +486,7 @@ "The project result is incomplete. Please retry downloading it.": "Das Projektergebnis ist unvollständig. Bitte laden Sie es erneut herunter.", "The saved result could not be retrieved. Please retry.": "Das gespeicherte Ergebnis konnte nicht abgerufen werden. Bitte versuchen Sie es erneut.", "The selected jobs have no stored results": "Die ausgewählten Aufträge haben keine gespeicherten Ergebnisse", + "The support prompt stores a local conversion count and timestamps to limit how often it appears.": "Der Unterstützungshinweis speichert lokal die Anzahl der Konvertierungen und Zeitstempel, um seine Anzeigehäufigkeit zu begrenzen.", "The text in the image, as Markdown": "Der Bildtext als Markdown", "Theme": "Design", "Theme:": "Design:", @@ -491,6 +497,7 @@ "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "Dieses gespeicherte Ergebnis ist nicht mehr verfügbar. Entfernen Sie den Eintrag und wählen Sie die Originaldatei für eine neue Konvertierung.", "This upload reservation expired. Choose the files again.": "Diese Upload-Reservierung ist abgelaufen. Wählen Sie die Dateien erneut aus.", "Time": "Zeit", + "Tips are made on Ko-fi and processed by its third-party payment provider, and LLMiser may receive supporter details from those services.": "Trinkgeld wird auf Ko-fi gegeben und vom externen Zahlungsanbieter verarbeitet. LLMiser kann von diesen Diensten Angaben zu Unterstützenden erhalten.", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "Für eine Meldung nennen Sie den vermuteten Rechtsverstoß, Dateinamen oder Auftragsreferenz und Zeitpunkt, Ihren Namen und Ihre E-Mail sowie eine Erklärung, dass die Meldung richtig und nach bestem Wissen erfolgt. Wir prüfen sie unverzüglich und teilen die Entscheidung mit. Bei Inhalts- oder Zugangsbeschränkungen erklären wir betroffenen Personen die Gründe.", "Toggle Recent Conversion Sessions Sidebar": "Seitenleiste mit letzten Konvertierungen umschalten", "Toggle Recent Conversion Sessions Sidebar (⌘B)": "Seitenleiste mit letzten Konvertierungen umschalten (⌘B)", diff --git a/frontend/lib/i18n/messages/en-US.json b/frontend/lib/i18n/messages/en-US.json index 4c17869..96dda9d 100644 --- a/frontend/lib/i18n/messages/en-US.json +++ b/frontend/lib/i18n/messages/en-US.json @@ -238,11 +238,13 @@ "Frequently asked questions": "Frequently asked questions", "Full formatted document": "Full formatted document", "GitHub": "GitHub", + "Glad that worked!": "Glad that worked!", "Heading-aligned chunks for vector embeddings": "Heading-aligned chunks for vector embeddings", "How can document preparation reduce LLM costs?": "How can document preparation reduce LLM costs?", "How can document preparation reduce LLM input costs?": "How can document preparation reduce LLM input costs?", "How do I convert documents with LLMiser?": "How do I convert documents with LLMiser?", "How does LLMiser help optimize LLM costs?": "How does LLMiser help optimize LLM costs?", + "I already did": "I already did", "If a result download fails, you can use its saved reference to request fresh download links without uploading or converting the file again. This sends the conversion reference to our service. Signed download links are not saved in local storage. Server retrieval stops when its files are deleted. Your cached Markdown copy can still be opened after server deletion.": "If a result download fails, you can use its saved reference to request fresh download links without uploading or converting the file again. This sends the conversion reference to our service. Signed download links are not saved in local storage. Server retrieval stops when its files are deleted. Your cached Markdown copy can still be opened after server deletion.", "If any part of these terms turns out to be invalid, the rest still applies.": "If any part of these terms turns out to be invalid, the rest still applies.", "If you have a complaint, write to devbehindyou@gmail.com first. We aim to answer within 14 days.": "If you have a complaint, write to devbehindyou@gmail.com first. We aim to answer within 14 days.", @@ -282,6 +284,7 @@ "LLMiser is a free LLM cost optimizer for document inputs. Convert PDFs, Word files, spreadsheets, slides, images and ZIP projects to Markdown, then trim unnecessary context before sending it to an AI assistant or retrieval pipeline.": "LLMiser is a free LLM cost optimizer for document inputs. Convert PDFs, Word files, spreadsheets, slides, images and ZIP projects to Markdown, then trim unnecessary context before sending it to an AI assistant or retrieval pipeline.", "LLMiser is a free service with no guaranteed uptime. We can change, pause or end all or part of it. Where we reasonably can, we'll announce big changes in advance.": "LLMiser is a free service with no guaranteed uptime. We can change, pause or end all or part of it. Where we reasonably can, we'll announce big changes in advance.", "LLMiser is busy right now. Please try again shortly.": "LLMiser is busy right now. Please try again shortly.", + "LLMiser is free and runs on a server I pay for. If it saved you time, a small tip helps keep it online.": "LLMiser is free and runs on a server I pay for. If it saved you time, a small tip helps keep it online.", "LLMiser is free. You keep full ownership of your files.": "LLMiser is free. You keep full ownership of your files.", "LLMiser is provided by DevBehindYou. Contact: devbehindyou@gmail.com.": "LLMiser is provided by DevBehindYou. Contact: devbehindyou@gmail.com.", "LLMiser is run by DevBehindYou. For anything about your data, write to devbehindyou@gmail.com.": "LLMiser is run by DevBehindYou. For anything about your data, write to devbehindyou@gmail.com.", @@ -317,6 +320,7 @@ "Markdown with headings, lists and pipe tables": "Markdown with headings, lists and pipe tables", "Markdown · UTF-8": "Markdown · UTF-8", "Max 5 sessions stored": "Max 5 sessions stored", + "Maybe later": "Maybe later", "Measure the result for your model": "Measure the result for your model", "Menu": "Menu", "Minimizes token density": "Minimizes token density", @@ -462,6 +466,7 @@ "Stored files changed. Refresh and try again.": "Stored files changed. Refresh and try again.", "Stripped of metadata & extra line breaks": "Stripped of metadata & extra line breaks", "Strips metadata & extra lines": "Strips metadata & extra lines", + "Support on Ko-fi": "Support on Ko-fi", "Supported documents and output": "Supported documents and output", "Switch to {v0} mode": "Switch to {v0} mode", "Task": "Task", @@ -481,6 +486,7 @@ "The project result is incomplete. Please retry downloading it.": "The project result is incomplete. Please retry downloading it.", "The saved result could not be retrieved. Please retry.": "The saved result could not be retrieved. Please retry.", "The selected jobs have no stored results": "The selected jobs have no stored results", + "The support prompt stores a local conversion count and timestamps to limit how often it appears.": "The support prompt stores a local conversion count and timestamps to limit how often it appears.", "The text in the image, as Markdown": "The text in the image, as Markdown", "Theme": "Theme", "Theme:": "Theme:", @@ -491,6 +497,7 @@ "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "This saved result is no longer available. Remove this entry and choose the original file to convert it again.", "This upload reservation expired. Choose the files again.": "This upload reservation expired. Choose the files again.", "Time": "Time", + "Tips are made on Ko-fi and processed by its third-party payment provider, and LLMiser may receive supporter details from those services.": "Tips are made on Ko-fi and processed by its third-party payment provider, and LLMiser may receive supporter details from those services.", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.", "Toggle Recent Conversion Sessions Sidebar": "Toggle Recent Conversion Sessions Sidebar", "Toggle Recent Conversion Sessions Sidebar (⌘B)": "Toggle Recent Conversion Sessions Sidebar (⌘B)", diff --git a/frontend/lib/i18n/messages/es.json b/frontend/lib/i18n/messages/es.json index e97d388..84ee6b9 100644 --- a/frontend/lib/i18n/messages/es.json +++ b/frontend/lib/i18n/messages/es.json @@ -238,11 +238,13 @@ "Frequently asked questions": "Preguntas frecuentes", "Full formatted document": "Documento completo con formato", "GitHub": "GitHub", + "Glad that worked!": "¡Qué bien que funcionó!", "Heading-aligned chunks for vector embeddings": "Fragmentos por encabezado para embeddings vectoriales", "How can document preparation reduce LLM costs?": "¿Cómo puede reducir costes de LLM la preparación de documentos?", "How can document preparation reduce LLM input costs?": "¿Cómo reduce la preparación de documentos los costes de entrada de LLM?", "How do I convert documents with LLMiser?": "¿Cómo convierto documentos con LLMiser?", "How does LLMiser help optimize LLM costs?": "¿Cómo ayuda LLMiser a optimizar los costes de LLM?", + "I already did": "Ya lo hice", "If a result download fails, you can use its saved reference to request fresh download links without uploading or converting the file again. This sends the conversion reference to our service. Signed download links are not saved in local storage. Server retrieval stops when its files are deleted. Your cached Markdown copy can still be opened after server deletion.": "Si falla la descarga de un resultado, puedes usar su referencia guardada para solicitar nuevos enlaces sin volver a subir ni convertir el archivo. Esto envía la referencia de conversión a nuestro servicio. Los enlaces de descarga firmados no se guardan en el almacenamiento local. Cuando se eliminan los archivos del servidor, ya no se pueden recuperar desde él. Tu copia de Markdown en caché sigue disponible después de la eliminación del servidor.", "If any part of these terms turns out to be invalid, the rest still applies.": "Si alguna parte de los términos resulta inválida, el resto sigue vigente.", "If you have a complaint, write to devbehindyou@gmail.com first. We aim to answer within 14 days.": "Si tienes una reclamación, escribe primero a devbehindyou@gmail.com. Intentamos responder en 14 días.", @@ -282,6 +284,7 @@ "LLMiser is a free LLM cost optimizer for document inputs. Convert PDFs, Word files, spreadsheets, slides, images and ZIP projects to Markdown, then trim unnecessary context before sending it to an AI assistant or retrieval pipeline.": "LLMiser es un optimizador gratuito de costes de LLM para documentos. Convierte PDF, Word, hojas de cálculo, diapositivas, imágenes y ZIP en Markdown y elimina contexto innecesario antes de enviarlo a un asistente de IA o sistema de recuperación.", "LLMiser is a free service with no guaranteed uptime. We can change, pause or end all or part of it. Where we reasonably can, we'll announce big changes in advance.": "LLMiser es gratuito y no garantiza disponibilidad continua. Podemos cambiar, pausar o terminar todo o parte del servicio. Anunciaremos cambios importantes con antelación cuando sea razonablemente posible.", "LLMiser is busy right now. Please try again shortly.": "LLMiser está ocupado. Inténtalo de nuevo en unos momentos.", + "LLMiser is free and runs on a server I pay for. If it saved you time, a small tip helps keep it online.": "LLMiser es gratis y funciona en un servidor que pago yo. Si te ahorró tiempo, una pequeña propina ayuda a mantenerlo en línea.", "LLMiser is free. You keep full ownership of your files.": "LLMiser es gratuito. Conservas la plena propiedad de tus archivos.", "LLMiser is provided by DevBehindYou. Contact: devbehindyou@gmail.com.": "LLMiser es ofrecido por DevBehindYou. Contacto: devbehindyou@gmail.com.", "LLMiser is run by DevBehindYou. For anything about your data, write to devbehindyou@gmail.com.": "LLMiser está gestionado por DevBehindYou. Para cuestiones sobre tus datos, escribe a devbehindyou@gmail.com.", @@ -317,6 +320,7 @@ "Markdown with headings, lists and pipe tables": "Markdown con encabezados, listas y tablas", "Markdown · UTF-8": "Markdown · UTF-8", "Max 5 sessions stored": "Máximo 5 conversiones guardadas", + "Maybe later": "Quizá más tarde", "Measure the result for your model": "Mide el resultado con tu modelo", "Menu": "Menú", "Minimizes token density": "Reduce la cantidad de tokens", @@ -462,6 +466,7 @@ "Stored files changed. Refresh and try again.": "Los archivos almacenados han cambiado. Actualiza e inténtalo de nuevo.", "Stripped of metadata & extra line breaks": "Sin metadatos ni saltos de línea adicionales", "Strips metadata & extra lines": "Elimina metadatos y líneas adicionales", + "Support on Ko-fi": "Apoyar en Ko-fi", "Supported documents and output": "Documentos admitidos y resultados", "Switch to {v0} mode": "Cambiar al modo {v0}", "Task": "Tarea", @@ -481,6 +486,7 @@ "The project result is incomplete. Please retry downloading it.": "El resultado del proyecto está incompleto. Vuelve a intentar descargarlo.", "The saved result could not be retrieved. Please retry.": "No se pudo recuperar el resultado guardado. Reintenta.", "The selected jobs have no stored results": "Los trabajos seleccionados no tienen resultados guardados", + "The support prompt stores a local conversion count and timestamps to limit how often it appears.": "El aviso de apoyo guarda un recuento local de conversiones y marcas de tiempo para limitar la frecuencia con que aparece.", "The text in the image, as Markdown": "El texto de la imagen en Markdown", "Theme": "Tema", "Theme:": "Tema:", @@ -491,6 +497,7 @@ "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "Este resultado guardado ya no está disponible. Elimina esta entrada y elige el archivo original para volver a convertirlo.", "This upload reservation expired. Choose the files again.": "La reserva de subida ha caducado. Selecciona los archivos de nuevo.", "Time": "Tiempo", + "Tips are made on Ko-fi and processed by its third-party payment provider, and LLMiser may receive supporter details from those services.": "Las propinas se envían en Ko-fi y las procesa su proveedor de pagos externo. LLMiser puede recibir datos de quienes apoyan a través de esos servicios.", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "Para denunciar, indica por qué crees que es ilegal, archivo o referencia del trabajo y hora, tu nombre y correo, y declara que la información es exacta y de buena fe. Revisaremos sin demora indebida y comunicaremos la decisión. Si restringimos contenido o acceso, explicaremos el motivo a la persona afectada.", "Toggle Recent Conversion Sessions Sidebar": "Alternar la barra de conversiones recientes", "Toggle Recent Conversion Sessions Sidebar (⌘B)": "Alternar conversiones recientes (⌘B)", diff --git a/frontend/lib/i18n/messages/ja.json b/frontend/lib/i18n/messages/ja.json index f2afae9..24b8fcd 100644 --- a/frontend/lib/i18n/messages/ja.json +++ b/frontend/lib/i18n/messages/ja.json @@ -238,11 +238,13 @@ "Frequently asked questions": "よくある質問", "Full formatted document": "書式付きの文書全体", "GitHub": "GitHub", + "Glad that worked!": "うまくいってよかったです!", "Heading-aligned chunks for vector embeddings": "ベクトル埋め込み用に見出し単位で分割", "How can document preparation reduce LLM costs?": "文書の準備でLLMコストはどう減る?", "How can document preparation reduce LLM input costs?": "文書の準備でLLMの入力コストはどう減る?", "How do I convert documents with LLMiser?": "LLMiserで文書を変換するには?", "How does LLMiser help optimize LLM costs?": "LLMiserでLLMコストをどう最適化できますか?", + "I already did": "すでに支援しました", "If a result download fails, you can use its saved reference to request fresh download links without uploading or converting the file again. This sends the conversion reference to our service. Signed download links are not saved in local storage. Server retrieval stops when its files are deleted. Your cached Markdown copy can still be opened after server deletion.": "結果のダウンロードに失敗した場合、保存された参照を使って新しいダウンロードリンクを取得できます。再アップロードや再変換は不要ですが、変換の参照情報は当サービスに送信されます。署名付きダウンロードリンクはローカルストレージに保存しません。サーバー上のファイルが削除されると取得できなくなりますが、キャッシュされたMarkdownのコピーは引き続き開けます。", "If any part of these terms turns out to be invalid, the rest still applies.": "規約の一部が無効となっても、その他の部分は引き続き適用されます。", "If you have a complaint, write to devbehindyou@gmail.com first. We aim to answer within 14 days.": "苦情はまずdevbehindyou@gmail.comへご連絡ください。14日以内の回答を目指します。", @@ -282,6 +284,7 @@ "LLMiser is a free LLM cost optimizer for document inputs. Convert PDFs, Word files, spreadsheets, slides, images and ZIP projects to Markdown, then trim unnecessary context before sending it to an AI assistant or retrieval pipeline.": "LLMiserは文書入力向けの無料LLMコスト最適化ツールです。PDF、Word文書、表計算、スライド、画像、ZIPプロジェクトをMarkdownに変換し、AIアシスタントや検索パイプラインに送る前に不要な情報を整理できます。", "LLMiser is a free service with no guaranteed uptime. We can change, pause or end all or part of it. Where we reasonably can, we'll announce big changes in advance.": "LLMiserは稼働時間を保証しない無料サービスです。全体または一部を変更、休止、終了する場合があります。合理的に可能な範囲で、大きな変更は事前にお知らせします。", "LLMiser is busy right now. Please try again shortly.": "LLMiserは現在混み合っています。しばらくしてから再試行してください。", + "LLMiser is free and runs on a server I pay for. If it saved you time, a small tip helps keep it online.": "LLMiserは無料で、私が費用を負担するサーバーで動いています。時間の節約になったなら、少額のチップでサービスの継続を支援できます。", "LLMiser is free. You keep full ownership of your files.": "LLMiserは無料です。ファイルの所有権はすべて利用者に帰属します。", "LLMiser is provided by DevBehindYou. Contact: devbehindyou@gmail.com.": "LLMiserはDevBehindYouが提供します。連絡先:devbehindyou@gmail.com。", "LLMiser is run by DevBehindYou. For anything about your data, write to devbehindyou@gmail.com.": "LLMiserはDevBehindYouが運営しています。データに関するお問い合わせはdevbehindyou@gmail.comへお送りください。", @@ -317,6 +320,7 @@ "Markdown with headings, lists and pipe tables": "見出し・リスト・パイプ表を含むMarkdown", "Markdown · UTF-8": "Markdown · UTF-8", "Max 5 sessions stored": "最大5件まで保存", + "Maybe later": "また今度", "Measure the result for your model": "使用モデルで効果を測定", "Menu": "メニュー", "Minimizes token density": "トークン数を抑制", @@ -462,6 +466,7 @@ "Stored files changed. Refresh and try again.": "保存済みファイルが変更されました。更新してもう一度お試しください。", "Stripped of metadata & extra line breaks": "メタデータと余分な改行を削除", "Strips metadata & extra lines": "メタデータと余分な行を削除", + "Support on Ko-fi": "Ko-fiで支援する", "Supported documents and output": "対応する文書と出力", "Switch to {v0} mode": "{v0}モードに切り替え", "Task": "タスク", @@ -481,6 +486,7 @@ "The project result is incomplete. Please retry downloading it.": "プロジェクトの結果が不完全です。ダウンロードを再試行してください。", "The saved result could not be retrieved. Please retry.": "保存された結果を取得できませんでした。再試行してください。", "The selected jobs have no stored results": "選択したジョブに保存結果がありません", + "The support prompt stores a local conversion count and timestamps to limit how often it appears.": "支援の案内は、表示頻度を抑えるために変換回数と日時を端末に保存します。", "The text in the image, as Markdown": "画像内のテキストをMarkdownに", "Theme": "テーマ", "Theme:": "テーマ:", @@ -491,6 +497,7 @@ "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "この保存結果は利用できなくなりました。項目を削除し、元のファイルを選んで再変換してください。", "This upload reservation expired. Choose the files again.": "アップロード予約の期限が切れました。ファイルを選び直してください。", "Time": "時間", + "Tips are made on Ko-fi and processed by its third-party payment provider, and LLMiser may receive supporter details from those services.": "チップはKo-fiで送信し、外部の決済事業者が処理します。LLMiserはそれらのサービスから支援者情報を受け取ることがあります。", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "違法と思われる内容の報告には、違法と考える理由、ファイル名またはジョブ番号と時刻、ご自身の氏名・メールアドレス、正確かつ誠実な報告である旨をお送りください。不当に遅滞することなく確認し、判断をお知らせします。内容やアクセスを制限する場合は、対象者に理由を説明します。", "Toggle Recent Conversion Sessions Sidebar": "変換履歴サイドバーを切り替え", "Toggle Recent Conversion Sessions Sidebar (⌘B)": "変換履歴サイドバーを切り替え(⌘B)", diff --git a/frontend/lib/i18n/messages/ru.json b/frontend/lib/i18n/messages/ru.json index 74548f1..ab8eabb 100644 --- a/frontend/lib/i18n/messages/ru.json +++ b/frontend/lib/i18n/messages/ru.json @@ -238,11 +238,13 @@ "Frequently asked questions": "Частые вопросы", "Full formatted document": "Полный форматированный документ", "GitHub": "GitHub", + "Glad that worked!": "Рады, что всё получилось!", "Heading-aligned chunks for vector embeddings": "Фрагменты по заголовкам для векторных представлений", "How can document preparation reduce LLM costs?": "Как подготовка документов может снизить расходы на LLM?", "How can document preparation reduce LLM input costs?": "Как подготовка документов снижает стоимость входных данных LLM?", "How do I convert documents with LLMiser?": "Как преобразовать документы в LLMiser?", "How does LLMiser help optimize LLM costs?": "Как LLMiser помогает оптимизировать расходы на LLM?", + "I already did": "Я уже поддержал(а)", "If a result download fails, you can use its saved reference to request fresh download links without uploading or converting the file again. This sends the conversion reference to our service. Signed download links are not saved in local storage. Server retrieval stops when its files are deleted. Your cached Markdown copy can still be opened after server deletion.": "Если результат не скачивается, сохранённая ссылка на преобразование позволяет запросить новые ссылки для скачивания без повторной загрузки и преобразования файла. При этом идентификатор преобразования отправляется нашему сервису. Подписанные ссылки для скачивания не сохраняются в локальном хранилище. После удаления файлов получить их с сервера нельзя. Сохранённую в браузере копию Markdown можно открыть и после удаления с сервера.", "If any part of these terms turns out to be invalid, the rest still applies.": "Недействительность части условий не влияет на остальные положения.", "If you have a complaint, write to devbehindyou@gmail.com first. We aim to answer within 14 days.": "При жалобе сначала напишите на devbehindyou@gmail.com. Мы стремимся ответить в течение 14 дней.", @@ -282,6 +284,7 @@ "LLMiser is a free LLM cost optimizer for document inputs. Convert PDFs, Word files, spreadsheets, slides, images and ZIP projects to Markdown, then trim unnecessary context before sending it to an AI assistant or retrieval pipeline.": "LLMiser — бесплатный инструмент оптимизации расходов на LLM для документов. Преобразуйте PDF, Word, таблицы, презентации, изображения и ZIP-проекты в Markdown, затем уберите лишний контекст перед отправкой ИИ-помощнику или системе поиска.", "LLMiser is a free service with no guaranteed uptime. We can change, pause or end all or part of it. Where we reasonably can, we'll announce big changes in advance.": "LLMiser — бесплатный сервис без гарантии непрерывной работы. Мы можем изменить, приостановить или завершить его полностью или частично. По возможности заранее сообщим о крупных изменениях.", "LLMiser is busy right now. Please try again shortly.": "LLMiser сейчас занят. Повторите немного позже.", + "LLMiser is free and runs on a server I pay for. If it saved you time, a small tip helps keep it online.": "LLMiser бесплатен и работает на сервере, за который я плачу. Если сервис сэкономил вам время, небольшие чаевые помогут поддерживать его работу.", "LLMiser is free. You keep full ownership of your files.": "LLMiser бесплатен. Вы полностью сохраняете права на свои файлы.", "LLMiser is provided by DevBehindYou. Contact: devbehindyou@gmail.com.": "LLMiser предоставляется DevBehindYou. Контакт: devbehindyou@gmail.com.", "LLMiser is run by DevBehindYou. For anything about your data, write to devbehindyou@gmail.com.": "LLMiser управляется DevBehindYou. По вопросам данных пишите на devbehindyou@gmail.com.", @@ -317,6 +320,7 @@ "Markdown with headings, lists and pipe tables": "Markdown с заголовками, списками и таблицами", "Markdown · UTF-8": "Markdown · UTF-8", "Max 5 sessions stored": "Хранится до 5 преобразований", + "Maybe later": "Может быть, позже", "Measure the result for your model": "Измерьте результат для вашей модели", "Menu": "Меню", "Minimizes token density": "Уменьшает количество токенов", @@ -462,6 +466,7 @@ "Stored files changed. Refresh and try again.": "Сохранённые файлы изменились. Обновите страницу и повторите попытку.", "Stripped of metadata & extra line breaks": "Без метаданных и лишних переносов строк", "Strips metadata & extra lines": "Удаляет метаданные и лишние строки", + "Support on Ko-fi": "Поддержать на Ko-fi", "Supported documents and output": "Поддерживаемые документы и результаты", "Switch to {v0} mode": "Переключить на {v0} тему", "Task": "Задача", @@ -481,6 +486,7 @@ "The project result is incomplete. Please retry downloading it.": "Результат проекта неполный. Повторите скачивание.", "The saved result could not be retrieved. Please retry.": "Не удалось получить сохранённый результат. Повторите попытку.", "The selected jobs have no stored results": "У выбранных заданий нет сохранённых результатов", + "The support prompt stores a local conversion count and timestamps to limit how often it appears.": "Запрос поддержки хранит на устройстве число конвертаций и отметки времени, чтобы ограничить частоту показа.", "The text in the image, as Markdown": "Текст изображения в Markdown", "Theme": "Тема", "Theme:": "Тема:", @@ -491,6 +497,7 @@ "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "Этот сохранённый результат больше недоступен. Удалите запись и выберите исходный файл для повторного преобразования.", "This upload reservation expired. Choose the files again.": "Срок резервирования истёк. Выберите файлы заново.", "Time": "Время", + "Tips are made on Ko-fi and processed by its third-party payment provider, and LLMiser may receive supporter details from those services.": "Чаевые отправляются через Ko-fi и обрабатываются сторонним платёжным оператором. LLMiser может получить от этих сервисов сведения о поддержавших пользователях.", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "Для сообщения укажите причину предполагаемой незаконности, имя файла или номер задания и время, ваши имя и email, а также заявление о точности и добросовестности сообщения. Мы рассмотрим его без неоправданной задержки и сообщим решение. При ограничении контента или доступа объясним причину затронутому лицу.", "Toggle Recent Conversion Sessions Sidebar": "Переключить панель недавних преобразований", "Toggle Recent Conversion Sessions Sidebar (⌘B)": "Переключить панель недавних преобразований (⌘B)", diff --git a/frontend/lib/i18n/messages/zh-CN.json b/frontend/lib/i18n/messages/zh-CN.json index ba5e31b..6e45ea5 100644 --- a/frontend/lib/i18n/messages/zh-CN.json +++ b/frontend/lib/i18n/messages/zh-CN.json @@ -238,11 +238,13 @@ "Frequently asked questions": "常见问题", "Full formatted document": "完整格式化文档", "GitHub": "GitHub", + "Glad that worked!": "很高兴转换成功!", "Heading-aligned chunks for vector embeddings": "按标题分块,用于向量嵌入", "How can document preparation reduce LLM costs?": "文档预处理如何降低LLM成本?", "How can document preparation reduce LLM input costs?": "文档预处理如何降低LLM输入成本?", "How do I convert documents with LLMiser?": "如何使用LLMiser转换文档?", "How does LLMiser help optimize LLM costs?": "LLMiser如何帮助优化LLM成本?", + "I already did": "我已支持", "If a result download fails, you can use its saved reference to request fresh download links without uploading or converting the file again. This sends the conversion reference to our service. Signed download links are not saved in local storage. Server retrieval stops when its files are deleted. Your cached Markdown copy can still be opened after server deletion.": "如果结果下载失败,您可以通过保存的转换引用请求新的下载链接,无需重新上传或转换文件。这会将转换引用发送至我们的服务。签名下载链接不会保存在本地存储中。服务器文件删除后将无法再次获取,但您仍可打开浏览器中缓存的Markdown副本。", "If any part of these terms turns out to be invalid, the rest still applies.": "如本条款的任何部分无效,其余部分仍然有效。", "If you have a complaint, write to devbehindyou@gmail.com first. We aim to answer within 14 days.": "如有投诉,请先联系devbehindyou@gmail.com。我们争取在14天内回复。", @@ -282,6 +284,7 @@ "LLMiser is a free LLM cost optimizer for document inputs. Convert PDFs, Word files, spreadsheets, slides, images and ZIP projects to Markdown, then trim unnecessary context before sending it to an AI assistant or retrieval pipeline.": "LLMiser是面向文档输入的免费LLM成本优化工具。将PDF、Word、电子表格、幻灯片、图像和ZIP项目转换为Markdown,再删去多余上下文后发送给AI助手或检索流程。", "LLMiser is a free service with no guaranteed uptime. We can change, pause or end all or part of it. Where we reasonably can, we'll announce big changes in advance.": "LLMiser是免费服务,不保证持续在线。我们可更改、暂停或终止全部或部分服务。在合理可行的情况下,会提前公告重大变更。", "LLMiser is busy right now. Please try again shortly.": "LLMiser当前繁忙,请稍后重试。", + "LLMiser is free and runs on a server I pay for. If it saved you time, a small tip helps keep it online.": "LLMiser 免费使用,服务器由我付费维护。如果它帮您节省了时间,一点打赏就能帮助它继续运行。", "LLMiser is free. You keep full ownership of your files.": "LLMiser免费使用,文件的全部所有权仍归您所有。", "LLMiser is provided by DevBehindYou. Contact: devbehindyou@gmail.com.": "LLMiser由DevBehindYou提供。联系方式:devbehindyou@gmail.com。", "LLMiser is run by DevBehindYou. For anything about your data, write to devbehindyou@gmail.com.": "LLMiser由DevBehindYou运营。有关数据的问题,请发送邮件至devbehindyou@gmail.com。", @@ -317,6 +320,7 @@ "Markdown with headings, lists and pipe tables": "包含标题、列表和管道表格的Markdown", "Markdown · UTF-8": "Markdown · UTF-8", "Max 5 sessions stored": "最多保存5次转换", + "Maybe later": "也许稍后", "Measure the result for your model": "针对您的模型衡量效果", "Menu": "菜单", "Minimizes token density": "尽量减少词元数量", @@ -462,6 +466,7 @@ "Stored files changed. Refresh and try again.": "已存储的文件发生变化。请刷新后重试。", "Stripped of metadata & extra line breaks": "移除元数据和多余换行", "Strips metadata & extra lines": "移除元数据和多余空行", + "Support on Ko-fi": "在 Ko-fi 上支持", "Supported documents and output": "支持的文档与输出", "Switch to {v0} mode": "切换为{v0}模式", "Task": "子任务", @@ -481,6 +486,7 @@ "The project result is incomplete. Please retry downloading it.": "项目结果不完整。请重试下载。", "The saved result could not be retrieved. Please retry.": "无法获取已保存的结果。请重试。", "The selected jobs have no stored results": "所选任务没有已存储的结果", + "The support prompt stores a local conversion count and timestamps to limit how often it appears.": "支持提示在本地保存转换次数和时间戳,以限制显示频率。", "The text in the image, as Markdown": "将图像中的文本输出为Markdown", "Theme": "主题", "Theme:": "主题:", @@ -491,6 +497,7 @@ "This saved result is no longer available. Remove this entry and choose the original file to convert it again.": "此保存结果已不可用。请移除此记录,然后选择原始文件重新转换。", "This upload reservation expired. Choose the files again.": "上传预留已过期。请重新选择文件。", "Time": "时间", + "Tips are made on Ko-fi and processed by its third-party payment provider, and LLMiser may receive supporter details from those services.": "打赏在 Ko-fi 上发起,由第三方支付服务商处理。LLMiser 可能从这些服务收到支持者的信息。", "To report content you believe is illegal, send us: why you think it's illegal, the file name or job reference and the time, your name and email, and a statement that your report is accurate and made in good faith. We'll review it without undue delay and tell you what we decided. If we restrict content or access, we explain the reason to the person affected.": "举报您认为非法的内容时,请提供:涉嫌非法的原因、文件名或任务编号及时间、您的姓名和邮箱,以及举报准确且出于善意的声明。我们会及时审查并告知决定。如限制内容或访问,将向受影响者说明原因。", "Toggle Recent Conversion Sessions Sidebar": "切换最近转换侧栏", "Toggle Recent Conversion Sessions Sidebar (⌘B)": "切换最近转换侧栏(⌘B)", diff --git a/frontend/lib/legal/policies.js b/frontend/lib/legal/policies.js index ff9cafc..0d9d44b 100644 --- a/frontend/lib/legal/policies.js +++ b/frontend/lib/legal/policies.js @@ -10,7 +10,7 @@ // category (Art. 13(1)(e) allows that) and available on request. export const LEGAL_VERSION = '2026-10-21'; -export const LEGAL_UPDATED_LABEL = '26 October 2026'; +export const LEGAL_UPDATED_LABEL = '13 November 2026'; export const OPERATOR = { name: 'DevBehindYou', @@ -90,9 +90,11 @@ export const PRIVACY_POLICY = { 'Your light or dark theme choice.', 'Your app language choice.', 'Which version of these documents you accepted, and when.', + 'The support prompt stores a local conversion count and timestamps to limit how often it appears.', 'Your last 5 conversions: the Markdown text when it fits, file details and a reference to the completed conversion. Clear them any time from the Recent panel.', ] }, { p: 'If a result download fails, you can use its saved reference to request fresh download links without uploading or converting the file again. This sends the conversion reference to our service. Signed download links are not saved in local storage. Server retrieval stops when its files are deleted. Your cached Markdown copy can still be opened after server deletion.' }, + { p: 'Tips are made on Ko-fi and processed by its third-party payment provider, and LLMiser may receive supporter details from those services.' }, { p: 'These items are needed for features you use, so the EU ePrivacy rules don\'t require a separate cookie consent for them.' }, ], }, diff --git a/frontend/lib/models/tipPrompt.js b/frontend/lib/models/tipPrompt.js new file mode 100644 index 0000000..cb689a5 --- /dev/null +++ b/frontend/lib/models/tipPrompt.js @@ -0,0 +1,67 @@ +export const TIP_PROMPT = Object.freeze({ + enabled: true, + url: 'https://ko-fi.com/devbehindyou', + firstShowAt: 3, + showDelayMs: 1500, + supportDays: 90, + alreadySupportedDays: 7, +}); + +const KEY = 'llmiser_tip_prompt_v1'; +const SESSION_KEY = 'llmiser_tip_prompt_shown'; + +function read(storage) { + const state = JSON.parse(storage.getItem(KEY) || '{}'); + return { + successes: Number.isSafeInteger(state.successes) ? Math.max(0, state.successes) : 0, + shownAt: Number.isFinite(state.shownAt) ? state.shownAt : null, + hiddenUntil: Number.isFinite(state.hiddenUntil) ? state.hiddenUntil : 0, + }; +} + +const day = time => new Date(time).toDateString(); + +/** Store only a count and timestamps. Both stores must be available to show. */ +export function createTipPrompt({ storage, session, now = Date.now, config = TIP_PROMPT }) { + function eligible(state, time) { + return config.enabled && !session.getItem(SESSION_KEY) && state.successes >= config.firstShowAt && + state.hiddenUntil <= time && (state.shownAt === null || day(state.shownAt) !== day(time)); + } + return { + recordSuccess() { + if (!config.enabled) return false; + try { + const state = read(storage); + state.successes = Math.min(config.firstShowAt, state.successes + 1); + storage.setItem(KEY, JSON.stringify(state)); + return true; + } catch { return false; } + }, + canShow() { + try { return eligible(read(storage), now()); } catch { return false; } + }, + markShown() { + try { + const state = read(storage), time = now(); + if (!eligible(state, time)) return false; + session.setItem(SESSION_KEY, '1'); + storage.setItem(KEY, JSON.stringify({ ...state, shownAt: time })); + return true; + } catch { return false; } + }, + snooze(action) { + if (!config.enabled) return; + try { + const state = read(storage), time = now(); + const until = new Date(time); + if (action === 'dismiss') { + until.setDate(until.getDate() + 1); + until.setHours(0, 0, 0, 0); + } else { + until.setDate(until.getDate() + (action === 'support' ? config.supportDays : config.alreadySupportedDays)); + } + storage.setItem(KEY, JSON.stringify({ ...state, hiddenUntil: until.getTime() })); + } catch { /* The card still closes when storage becomes unavailable. */ } + }, + }; +} diff --git a/frontend/public/support/llmiser-tip-banner-static@2x.png b/frontend/public/support/llmiser-tip-banner-static@2x.png new file mode 100644 index 0000000..e45fed8 Binary files /dev/null and b/frontend/public/support/llmiser-tip-banner-static@2x.png differ diff --git a/frontend/public/support/llmiser-tip-banner.gif b/frontend/public/support/llmiser-tip-banner.gif new file mode 100644 index 0000000..54204cd Binary files /dev/null and b/frontend/public/support/llmiser-tip-banner.gif differ diff --git a/frontend/public/support/llmiser-tip-banner@2x.gif b/frontend/public/support/llmiser-tip-banner@2x.gif new file mode 100644 index 0000000..b9c2104 Binary files /dev/null and b/frontend/public/support/llmiser-tip-banner@2x.gif differ diff --git a/frontend/test/tipPrompt.test.mjs b/frontend/test/tipPrompt.test.mjs new file mode 100644 index 0000000..08f7a43 --- /dev/null +++ b/frontend/test/tipPrompt.test.mjs @@ -0,0 +1,55 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createTipPrompt, TIP_PROMPT } from '../lib/models/tipPrompt.js'; + +function memory() { + const data = new Map(); + return { getItem: key => data.get(key), setItem: (key, value) => data.set(key, value) }; +} + +test('third success is eligible, with one showing per local day and per tab session', () => { + let time = new Date(2026, 10, 13, 23, 59, 59, 999).getTime(); + const storage = memory(); + const open = () => createTipPrompt({ storage, session: memory(), now: () => time }); + const prompt = open(); + assert.equal(prompt.canShow(), false); + prompt.recordSuccess(); + assert.equal(prompt.canShow(), false); + prompt.recordSuccess(); + assert.equal(prompt.canShow(), false); + prompt.recordSuccess(); + assert.equal(prompt.markShown(), true); + prompt.snooze('dismiss'); + assert.equal(open().canShow(), false); + time += 1; + assert.equal(prompt.canShow(), false); + assert.equal(open().canShow(), true); +}); + +for (const [action, days] of [['support', 90], ['already-supported', 7]]) { + test(`${action} snoozes for ${days} local days`, () => { + let time = new Date(2026, 10, 13, 12).getTime(); + const storage = memory(); + const open = () => createTipPrompt({ storage, session: memory(), now: () => time }); + const prompt = open(); + for (let i = 0; i < 3; i++) prompt.recordSuccess(); + assert.equal(prompt.markShown(), true); + prompt.snooze(action); + const end = new Date(time); + end.setDate(end.getDate() + days); + time = end.getTime() - 1; + assert.equal(open().canShow(), false); + time++; + assert.equal(open().canShow(), true); + }); +} + +test('the kill switch and blocked storage prevent the card', () => { + const blocked = { getItem() { throw Error('denied'); }, setItem() { throw Error('denied'); } }; + const prompt = createTipPrompt({ storage: blocked, session: memory() }); + assert.equal(prompt.recordSuccess(), false); + assert.equal(prompt.markShown(), false); + const disabled = createTipPrompt({ storage: memory(), session: memory(), config: { ...TIP_PROMPT, enabled: false } }); + assert.equal(disabled.recordSuccess(), false); + assert.equal(disabled.canShow(), false); +}); diff --git a/frontend/viewmodels/useConverterScreenViewModel.js b/frontend/viewmodels/useConverterScreenViewModel.js index 1300096..1cc8953 100644 --- a/frontend/viewmodels/useConverterScreenViewModel.js +++ b/frontend/viewmodels/useConverterScreenViewModel.js @@ -1,6 +1,6 @@ 'use client'; -import { useCallback, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { generateSampleSession } from '../lib/models/sessionRepository'; import { useThemeViewModel } from './useThemeViewModel'; import { useServerStatusViewModel } from './useServerStatusViewModel'; @@ -10,6 +10,7 @@ import { useConverterViewModel } from './useConverterViewModel'; import { useExportViewModel } from './useExportViewModel'; import { useKeyboardShortcuts } from './useKeyboardShortcuts'; import { useConsentViewModel } from './useConsentViewModel'; +import { useTipPrompt } from './useTipPrompt'; /** * ViewModel for the converter screen (app/page.js). Composes the feature @@ -23,6 +24,9 @@ export function useConverterScreenViewModel({ openFilePicker }) { const { theme, toggleTheme } = useThemeViewModel(); const { serverStatus, wakeCountdown, recheck } = useServerStatusViewModel(); const { toast, showToast } = useToastViewModel(); + const tipBlocked = useRef(false); + const tip = useTipPrompt(tipBlocked); + const { recordSuccess, cancel: cancelTip } = tip; const recent = useRecentSessionsViewModel(); const { saveSession, setActiveSessionId, deleteSession: removeSession, clearSessions: wipeSessions } = recent; @@ -45,7 +49,10 @@ export function useConverterScreenViewModel({ openFilePicker }) { ); const converter = useConverterViewModel({ - onConverted: handleConverted, + onConverted(result, meta) { + handleConverted(result, meta); + if (meta.item.file && !meta.item.recovery?.job_id) recordSuccess(result.id); + }, onResultRetained: handleConverted, onNetworkFailure: recheck, onNotice: showToast, @@ -54,6 +61,7 @@ export function useConverterScreenViewModel({ openFilePicker }) { activeResult: converter.activeResult, results: converter.results, onNotice: showToast, + onDownloaded: tip.onDownloaded, }); const { loadSession } = converter; @@ -88,6 +96,10 @@ export function useConverterScreenViewModel({ openFilePicker }) { const [blogOpen, setBlogOpen] = useState(false); const [apiOpen, setApiOpen] = useState(false); const [legalModal, setLegalModal] = useState(null); // 'privacy' | 'terms' | null + const blocked = !consentAccepted || converter.isBusy || Boolean(converter.quotaError) || + converter.items.some(item => item.status === 'error') || sidebarOpen || menuOpen || blogOpen || apiOpen || Boolean(legalModal); + tipBlocked.current = blocked; + useEffect(() => { if (blocked) cancelTip(); }, [blocked, cancelTip]); const sidebarOpenRef = useRef(sidebarOpen); sidebarOpenRef.current = sidebarOpen; @@ -175,6 +187,7 @@ export function useConverterScreenViewModel({ openFilePicker }) { wakeCountdown, recheck, toast, + tip: { ...tip, blocked }, converter: { ...converter, convertAll, retry }, exporter, recent: { diff --git a/frontend/viewmodels/useExportViewModel.js b/frontend/viewmodels/useExportViewModel.js index 329c3b5..7dd5936 100644 --- a/frontend/viewmodels/useExportViewModel.js +++ b/frontend/viewmodels/useExportViewModel.js @@ -7,11 +7,11 @@ import { snapshotWithPendingEdits } from '../lib/models/editorExport'; const COPIED_MS = 1800; /** Copy / .md / .zip commands for the active result and the whole batch. */ -export function useExportViewModel({ activeResult, results, onNotice }) { +export function useExportViewModel({ activeResult, results, onNotice, onDownloaded }) { const [copied, setCopied] = useState(false); const timerRef = useRef(null); - const latestRef = useRef({ activeResult, results, onNotice }); - latestRef.current = { activeResult, results, onNotice }; + const latestRef = useRef({ activeResult, results, onNotice, onDownloaded }); + latestRef.current = { activeResult, results, onNotice, onDownloaded }; const editorsRef = useRef(new Set()); const registerEditor = useCallback(takePending => { @@ -38,12 +38,18 @@ export function useExportViewModel({ activeResult, results, onNotice }) { }, [snapshot]); const downloadActive = useCallback(() => { - downloadMarkdown(snapshot().activeResult); + const result = snapshot().activeResult; + if (!result) return; + downloadMarkdown(result); + latestRef.current.onDownloaded?.([result.id]); }, [snapshot]); const downloadAll = useCallback(async () => { try { - await downloadMarkdownZip(snapshot().results); + const results = snapshot().results; + if (!results.length) return; + await downloadMarkdownZip(results); + latestRef.current.onDownloaded?.(results.map(result => result.id)); } catch (err) { console.error('ZIP export failed:', err); latestRef.current.onNotice?.('Could not build the ZIP file'); diff --git a/frontend/viewmodels/useTipPrompt.js b/frontend/viewmodels/useTipPrompt.js new file mode 100644 index 0000000..57ab4ba --- /dev/null +++ b/frontend/viewmodels/useTipPrompt.js @@ -0,0 +1,34 @@ +'use client'; + +import { useCallback, useEffect, useRef, useState } from 'react'; +import { createTipPrompt, TIP_PROMPT } from '../lib/models/tipPrompt'; + +function browserPrompt() { + try { return createTipPrompt({ storage: window.localStorage, session: window.sessionStorage }); } + catch { return null; } +} + +export function useTipPrompt(blocked) { + const [pending, setPending] = useState(false); + const freshResults = useRef(new Set()); + const timer = useRef(null); + const cancel = useCallback(() => { clearTimeout(timer.current); setPending(false); }, []); + const recordSuccess = useCallback(id => { + if (freshResults.current.has(id)) return; + if (browserPrompt()?.recordSuccess()) freshResults.current.add(id); + }, []); + const onDownloaded = useCallback(ids => { + if (!ids.some(id => freshResults.current.has(id)) || !browserPrompt()?.canShow()) return; + clearTimeout(timer.current); + timer.current = setTimeout(() => { + if (document.hasFocus() && !blocked.current && !document.querySelector('[aria-modal="true"], dialog[open]')) setPending(true); + }, TIP_PROMPT.showDelayMs); + }, [blocked]); + const dismiss = useCallback(action => { + browserPrompt()?.snooze(action); + cancel(); + }, [cancel]); + const markShown = useCallback(() => browserPrompt()?.markShown() === true, []); + useEffect(() => () => clearTimeout(timer.current), []); + return { pending, recordSuccess, onDownloaded, cancel, dismiss, markShown }; +}