Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

オフラインでも時間割を確認できるように #601

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .lintstagedrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ const tsconfigFilename = "tsconfig.staged.json";

const typecheckOnlyStaged = (stagedFilenames) => {
const tsconfig = JSON.parse(fs.readFileSync("tsconfig.json"));
tsconfig.include = stagedFilenames;
tsconfig.include = stagedFilenames.filter((filename) =>
filename.includes("/src/")
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/tsconfig.ts"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],が指定されていることからわかるように、typecheckOnlyStaged/src 以下の型検査のみに関心を持っている。したがってここでは/src以下を検査するようにして /serviceworkers 以下は除外している。

なお yarn typecheck/serviceworkers 以下の型検査はちゃんと走る。

);
fs.writeFileSync(tsconfigFilename, JSON.stringify(tsconfig));
return `yarn typecheck --project ${tsconfigFilename}`;
};
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"license": "MIT",
"scripts": {
"dev": "vite",
"typecheck": "vue-tsc --noEmit",
"build": "yarn typecheck && vite build",
"typecheck": "yarn build-serviceworker --noEmit && vue-tsc --noEmit",
"build": "yarn typecheck && vite build && yarn build-serviceworker",
"build:staging": "vite build --mode staging",
"preview": "yarn build && vite preview --port 8080",
"format": "prettier ./src --check",
Expand All @@ -15,6 +15,7 @@
"test": "jest",
"apigen": "rm -rf src/api && npx openapi2aspida",
"prepare": "husky install && rimraf ./node_modules/@types/react",
"build-serviceworker": "tsc -p serviceworkers/tsconfig.json",
"storybook": "start-storybook -p 6006",
"build-storybook": "yarn typecheck && build-storybook"
},
Expand Down
71 changes: 71 additions & 0 deletions serviceworkers/fallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import * as dotenv from "dotenv";

dotenv.config();

const CACHE_NAME = "TwinteFallback";
const VERSIONS = ["v1"];

let base_url: string;

if (process.env.NODE_ENV === "development") {
base_url = process.env.BASE_URL || "http://localhost:4000";
} else {
base_url = process.env.BASE_URL;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: 本番ビルド時に環境変数を注入するように設定をする

Production で dotenv (に限らずコミットされるファイルに環境値がかかれたもの)を使用するのは微妙だと思うため。
なぜならアプリが環境を意識しないための環境変数なのに、環境(ファイル)を意識しては元も子もない。

}

declare const self: ServiceWorkerGlobalScope;

self.addEventListener("install", () => {
VERSIONS.slice(0, Math.max(0, VERSIONS.length - 2)).forEach(
async (version) => {
await caches.delete(getCacheName(CACHE_NAME, version));
}
);
});

self.addEventListener("fetch", (event) => {
const request = event.request;

if (request.method !== "GET") return;
if (
!(
request.url.startsWith(base_url) ||
request.url.startsWith("https://fonts.googleapis.com/") ||
request.url.startsWith("https://fonts.gstatic.com/")
Comment on lines +32 to +34
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Google Fonts がないとオフライン時にアイコンが表示されないのでキャッシュをしている。

)
)
return;

event.respondWith(getResponseWithCaching(request));
});

const getCacheName = (name: string, version: string) => `${name}_${version}`;

const getResponseWithCaching = async (request: Request): Promise<Response> => {
const cache = await caches.open(
getCacheName(CACHE_NAME, VERSIONS[VERSIONS.length - 1])
);

let response: Response | undefined;

const hasCredentials = request.url.startsWith(base_url);

try {
response = await fetch(
request,
hasCredentials
? {
credentials: "include",
}
: {}
);
} catch (error) {
console.error(error);
response = await cache.match(request.url);
if (!response) throw new Error("There is no cache");
}

if (response.ok) cache.put(request, response.clone());

return response;
};
18 changes: 18 additions & 0 deletions serviceworkers/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"include": ["./**/*.ts"],
"compilerOptions": {
"sourceMap": true,
"module": "esnext",
"moduleResolution": "node",
"preserveValueImports": false,
"esModuleInterop": true,
"importsNotUsedAsValues": "remove",
"baseUrl": ".",
"paths": {
"~/*": ["./*"]
},
"lib": ["ES2021", "WebWorker"],
"types": ["node"],
"outDir": "../dist"
}
}
Comment on lines +1 to +18
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/src 以下のページスクリプトと /serviceworker は別世界なのでそれぞれ独自に tsconfig を持ちたい。

例えば /serviceworkers/tsconfig.ts"extends": "@vue/tsconfig/tsconfig.web.json" という設定値を持ったり、
/tsconfig.ts"lib": ["ES2021", "WebWorker"], という設定値をもつのはおかしい

11 changes: 2 additions & 9 deletions src/ui/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
</template>

<script setup lang="ts">
import { onErrorCaptured, onMounted, ref } from "vue";
import { onErrorCaptured, ref } from "vue";
import { useRouter } from "vue-router";
import {
InternalServerError,
Expand All @@ -32,14 +32,7 @@ setSetting();

const router = useRouter();

/** unregister service worker (v2) */
onMounted(() => {
navigator.serviceWorker.getRegistrations().then(function (registrations) {
for (let registration of registrations) {
registration.unregister();
}
});
});
Comment on lines -35 to -42
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

v2 公開終了から 1 年半が経過したので流石にもういらないと思われる。

navigator.serviceWorker.register("/fallback.js");

/** error */
const errorMessage = ref("");
Expand Down