Skip to content

Commit

Permalink
Update editor.defaultFormatter and start script
Browse files Browse the repository at this point in the history
  • Loading branch information
m7medVision committed Jan 22, 2024
1 parent 4d56181 commit 7dd4827
Show file tree
Hide file tree
Showing 10 changed files with 93 additions and 36 deletions.
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"editor.defaultFormatter": "denoland.vscode-deno"
},
"[typescript]": {
"editor.defaultFormatter": "denoland.vscode-deno"
"editor.defaultFormatter": "vscode.typescript-language-features"
},
"[javascriptreact]": {
"editor.defaultFormatter": "denoland.vscode-deno"
Expand Down
4 changes: 2 additions & 2 deletions components/Courses.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import CourseCard from "./CourseCard.tsx";
import ProgressSection from "@/islands/ProgressSection.tsx";

export default function Courses(
{ courses }: {
{ courses, total }: {
courses: (Course | CourseGroup)[];
total: number;
},
) {
const total = getNumberOfCourses(courses);
return (
<>
<div className="py-2 bg-base-300 p-4 rounded-md">
Expand Down
5 changes: 2 additions & 3 deletions deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"check": "deno fmt --check && deno lint && deno check **/*.ts && deno check **/*.tsx",
"cli": "echo \"import '\\$fresh/src/dev/cli.ts'\" | deno run --unstable -A -",
"manifest": "deno task cli manifest $(pwd)",
"start": "deno run -A --watch=static/,routes/ --unstable dev.ts",
"start": "deno run -A --watch=static/,routes/,plugins/ --unstable dev.ts",
"build": "deno run --unstable -A dev.ts build",
"preview": "deno run --unstable -A main.ts",
"update": "deno run -A -r https://fresh.deno.dev/update ."
Expand All @@ -23,8 +23,7 @@
"tailwindcss/plugin": "npm:/[email protected]/plugin.js",
"$std/": "https://deno.land/[email protected]/",
"$gfm": "https://deno.land/x/[email protected]/mod.ts",
"daisyui": "npm:daisyui@latest",
"zod": "https://esm.sh/[email protected]"
"daisyui": "npm:daisyui@latest"
},
"compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "preact" },
"nodeModulesDir": true
Expand Down
7 changes: 5 additions & 2 deletions fresh.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { defineConfig } from "$fresh/server.ts";
import tailwind from "$fresh/plugins/tailwind.ts";

import SW_cache from "@/plugins/sw-page-json-builder.ts";
export default defineConfig({
plugins: [tailwind()],
plugins: [tailwind(),
// fresh_cache,
SW_cache(),
],
});
44 changes: 44 additions & 0 deletions plugins/sw-page-json-builder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Plugin, PluginMiddleware } from "$fresh/server.ts";
import * as path from "https://deno.land/[email protected]/path/mod.ts";
import { getFlatSlugs } from "@/utils/course.ts";
export default function SW_cache(
): Plugin {
let staticDir = path.join(Deno.cwd(), "static");
const SW_cacheMiddleware: PluginMiddleware = {
path: "/",
middleware: {
handler: async (_, ctx) => {
if (ctx.url.pathname == "/sw-cache.json") {
const resp = new Response(JSON.stringify(await getFlatSlugs()), {
headers: {
"content-type": "application/json",
}
});
return resp;
}
return ctx.next()
},
},
};

const middlewares: Plugin["middlewares"] = [];

return {
name: "sw-cache",
async configResolved(config) {
if (config.dev) {
staticDir = config.staticDir;
middlewares.push(SW_cacheMiddleware);
}
},
middlewares,
async buildStart(config) {
staticDir = config.staticDir;
console.log("SW_cache buildStart");
const outFilePath = path.join(staticDir, "sw-cache.json");
const slugs = await getFlatSlugs();
const data = JSON.stringify(slugs);
await Deno.writeTextFile(outFilePath, data);
},
};
}
2 changes: 1 addition & 1 deletion routes/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default async function Layout(req: Request, ctx: FreshContext) {
rel="stylesheet"
/>
<script src="/theme-loader.js"></script>
<script src="/sw-rg.js"></script>
<script type="module" src="/sw-rg.js"></script>
</head>
<body>
<div class="h-screen">
Expand Down
10 changes: 7 additions & 3 deletions routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,24 @@ import { Head } from "$fresh/runtime.ts";
import { Handlers } from "$fresh/server.ts";
import { PageProps } from "$fresh/server.ts";

import { getCourses, getNumberOfCourses } from "../utils/course.ts";
import { getCourses } from "../utils/course.ts";
import { Course, CourseGroup } from "../utils/types.ts";
import { cache } from "../utils/course-cache.ts";

import Footer from "../components/Footer.tsx";
import Courses from "../components/Courses.tsx";
import { getNumberOfCourses } from "@/utils/course.ts";

interface Props {
courses: (Course | CourseGroup)[];
total: number;
}
export const handler: Handlers<Props> = {
async GET(_req, ctx) {
const courses = await getCourses(cache);
const total = await getNumberOfCourses();
return ctx.render({
total,
courses: courses.courses,
});
},
Expand All @@ -24,7 +28,7 @@ export const handler: Handlers<Props> = {
export default function BlogIndexPage(
props: PageProps<Props>,
) {
const { courses } = props.data;
const { courses,total } = props.data;
return (
<>
<Head>
Expand All @@ -43,7 +47,7 @@ export default function BlogIndexPage(
/>
</Head>
<main className="max-w-screen-md px-4 pt-8 mx-auto mb-6">
<Courses courses={courses} />
<Courses total={total} courses={courses} />
</main>
<Footer />
</>
Expand Down
4 changes: 3 additions & 1 deletion static/sw-rg.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js")
navigator.serviceWorker.register("/sw.js", {
type: 'module'
})
}
15 changes: 12 additions & 3 deletions static/sw.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
const CACHE_NAME = 'static-cache-v1';
self.addEventListener('install', function(event) {
// TODO:
self.addEventListener('install', async function(event) {
const resp = await fetch('/sw-cache.json');
const FILES_TO_CACHE = await resp.json();
console.log('Installing Service Worker...');
console.log('Caching Files...');
console.log(FILES_TO_CACHE.join('\n'));
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll(FILES_TO_CACHE);
})
);
});
self.addEventListener('activate', function(event) {

});
self.addEventListener('fetch', function(event) {
console.log('Fetching:', event.request.url);
// console.log('Fetching:', event.request.url);
event.respondWith(
caches.match(event.request).then(function(response) {
// I KNOW THIS IS NOT THE BEST WAY TO DO THIS
Expand Down
36 changes: 16 additions & 20 deletions utils/course.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { extract } from "https://deno.land/[email protected]/encoding/front_matter.ts"
import { Course, CourseAttributes, CourseGroup } from "../utils/types.ts";

export let CoursesCount = 0;
export let FlatSlugsCache: string[] = [];

export async function getGroupJsonData(
groupPath: string,
Expand Down Expand Up @@ -104,11 +105,16 @@ export async function getCourses(
cache.courses = merged;

const endTime = performance.now();
console.log(`Caching data took ${(endTime - startTime) / 1000} seconds`);
// console.log(`Caching data took ${(endTime - startTime) / 1000} seconds`);
return cache;
}

export function getNumberOfCourses(courses: (Course | CourseGroup)[]) {
export async function getFlatSlugs() {
if (FlatSlugsCache.length > 0) {
// console.log("Using cache");
return FlatSlugsCache;
}
const { courses } = await getCourses();
const slugs = courses.map((c) => {
if ("courses" in c) {
c.courses.sort((a, b) => a.order - b.order);
Expand All @@ -117,35 +123,25 @@ export function getNumberOfCourses(courses: (Course | CourseGroup)[]) {
return c.slug.replace("\\", "/");
});
const FlatSlugs = slugs.flat();
FlatSlugsCache = FlatSlugs;
return FlatSlugs;
}
export async function getNumberOfCourses() {
const FlatSlugs = await getFlatSlugs();
return FlatSlugs.length;
}

export async function findNextCourse(slug: string) {
const { courses } = await getCourses();
const slugs = courses.map((c) => {
if ("courses" in c) {
c.courses.sort((a, b) => a.order - b.order);
return c.courses.map((c) => c.slug.replace("\\", "/"));
}
return c.slug.replace("\\", "/");
});
const FlatSlugs = slugs.flat();
const FlatSlugs = await getFlatSlugs();
const index = FlatSlugs.indexOf(slug);
if (index === -1) {
return slug;
}
return FlatSlugs[index + 1];
}

export async function findPrevCourse(slug: string) {
const { courses } = await getCourses();
const slugs = courses.map((c) => {
if ("courses" in c) {
c.courses.sort((a, b) => a.order - b.order);
return c.courses.map((c) => c.slug.replace("\\", "/"));
}
return c.slug.replace("\\", "/");
});
const FlatSlugs = slugs.flat();
const FlatSlugs = await getFlatSlugs();
const index = FlatSlugs.indexOf(slug);
if (index === 1) {
return slug;
Expand Down

0 comments on commit 7dd4827

Please sign in to comment.