Просмотр исходного кода

Add download button for recipes

Lee Morgan 1 неделя назад
Родитель
Сommit
503bcfbb57
1 измененных файлов с 21 добавлено и 1 удалено
  1. 21 1
      src/routes/recipe/[recipeId]/+page.svelte

+ 21 - 1
src/routes/recipe/[recipeId]/+page.svelte

@@ -23,6 +23,26 @@
         notify("success", "Link copied to clipboard");
     }
 
+    const download = ()=>{
+        const json = JSON.stringify({
+            name: data.recipe.name,
+            ingredients: data.recipe.ingredients,
+            steps: data.recipe.steps,
+            notes: data.recipe.notes,
+        });
+        const blob = new Blob([json], {type: "application/json"});
+        const url = URL.createObjectURL(blob);
+
+        const a = document.createElement("a");
+        a.href = url;
+        a.download = `${data.recipe.name.replaceAll(" ", "_")}.json`;
+        document.body.appendChild(a);
+        a.click();
+        a.remove();
+
+        URL.revokeObjectURL(url);
+    }
+
     onMount(()=>{
         const stop = attachVisibilityReacquire(()=>on);
 
@@ -85,7 +105,7 @@
                 <div class="shareMenu" role="menu">
                     <button role="menuitem" onclick={copyLink}>Copy link</button>
                     <a href="/recipe/{data.recipe.id}/print" role="menuitem">Print</a>
-                    <button role="menuitem">Download</button>
+                    <button role="menuitem" onclick={download}>Download</button>
                 </div>
             {/if}
         </div>