diff --git a/.gitignore b/.gitignore index 6aaf99b..c9721ac 100644 --- a/.gitignore +++ b/.gitignore @@ -132,3 +132,4 @@ dist # Build output and local browser check screenshots _site/ shots/ +.pwa-profile-*/ diff --git a/AGENTS.md b/AGENTS.md index b447a6c..7908939 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,6 +7,7 @@ Source of [tools.halit.org](https://tools.halit.org/): small browser tools Halit - `scripts/build.mjs` writes static HTML into `_site/`. Page copy lives in `scripts/content.mjs`; change those, never the output. No framework and no runtime dependencies; esbuild is the one dev dependency and minifies the page scripts. - `tokens.css` (the personal design standard, see `DESIGN.md`) and `public/site.css` are joined and minified into one `site.css`. - Each tool is a pure module in `src/` (tested with `node:test`) plus a small page script. Pages ship a Content Security Policy whose only outside connection is the Cloudflare Web Analytics beacon. Keep it that way: the pages promise that pasted text never leaves the device. +- The site is an installable app. Each language has its own manifest (`/site.webmanifest`, `/tr/site.webmanifest`) and `src/sw.js` is the service worker: pages network first with the cached copy as the offline fallback, everything else cache first. The build names the cache after a hash of every precached file and adds `?v=` to CSS and JS URLs, so a deploy always installs a fresh cache. A new page script goes into `SCRIPTS` in `build.mjs`. Geist is self-hosted in `public/fonts/`. - `public/db8734a2d48c2e0e5cf2ef632940201f.txt` is the IndexNow key. After a deploy that adds or changes pages, post their URLs to `https://api.indexnow.org/indexnow` with that key. - `.github/workflows/pages.yml` tests and builds every PR and deploys `main` to GitHub Pages. `public/CNAME` holds the custom domain; DNS is a DNS-only CNAME `tools -> halitsever.github.io` in the halit.org Cloudflare zone. @@ -23,6 +24,8 @@ Source of [tools.halit.org](https://tools.halit.org/): small browser tools Halit npm test && npm run check ``` +`npm run check:pwa` is the lighter check for the app side: manifests, service worker, every page offline, cache turnover after a deploy and the install button. + ## Conventions - Conventional-commit subject lines only, in English, with no body or trailer. diff --git a/Readme.md b/Readme.md index dcbdac7..16597ee 100644 --- a/Readme.md +++ b/Readme.md @@ -36,6 +36,7 @@ Small tools Halit Sever uses himself, at tools.halit.org. They run in your brows - [**Kelime ve karakter sayacı**](https://tools.halit.org/tr/karakter-sayaci/) - word and character counter: words, characters with and without spaces, letters, sentences and paragraphs as you type, a reading time at a speed you set, a character limit and a count for the selected part. Words follow Unicode word boundaries (UAX #29), so apostrophes such as İstanbul'da keep a word whole; characters are grapheme clusters, so an emoji counts once. Turkish only. - [**Word frequency counter**](https://tools.halit.org/word-frequency-counter/) - ranks every word in a text by how often it appears, with its count and its share of all words (keyword density). Counts two- and three-word phrases inside one sentence, leaves out English stop words on request, has a Turkish casing option for I and İ, and copies the table for a spreadsheet or downloads it as CSV. English only. - **Stays on your device** - every tool is plain JavaScript in the page. A Content Security Policy blocks connections to any server except the Cloudflare Web Analytics page-view beacon, so pasted text cannot be sent anywhere. +- **Installable and offline** - Chrome and Edge can install the site as an app, and iPhone or iPad can add it to the home screen. After one visit a service worker keeps every tool and the Geist font cached, so the tools work without a connection. - **English and Turkish** - each page has a Turkish twin written in Turkish, paired with `hreflang`.

@@ -49,7 +50,7 @@ npm test # unit tests for the cleaning functions (node:test) npm run build # writes the site to _site/ ``` -`npm run check` builds and then drives the pages in headless Chrome at 1440 and 390 px. It needs `playwright-core` and Chrome on the machine; set `PLAYWRIGHT_CORE` and `CHROME` if they are not in the default places. `npm run og` renders the social images into `public/og/` the same way. +`npm run check` builds and then drives the pages in headless Chrome at 1440 and 390 px; `npm run check:pwa` checks the manifests, the service worker, offline use of every page and the install button. It needs `playwright-core` and Chrome on the machine; set `PLAYWRIGHT_CORE` and `CHROME` if they are not in the default places. `npm run og` renders the social images into `public/og/` the same way. The Pages workflow tests and builds every pull request and deploys `main` to [tools.halit.org](https://tools.halit.org/). diff --git a/package.json b/package.json index 000c195..658ce19 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "build": "node scripts/build.mjs", "test": "node --test test/*.test.mjs", "check": "node scripts/build.mjs && node scripts/browser-check.mjs", + "check:pwa": "node scripts/build.mjs && node scripts/pwa-check.mjs", "og": "node scripts/og.mjs" }, "engines": { diff --git a/public/fonts/OFL.txt b/public/fonts/OFL.txt new file mode 100644 index 0000000..61f6f4b --- /dev/null +++ b/public/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font.git) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/public/fonts/geist-cyrillic-ext.woff2 b/public/fonts/geist-cyrillic-ext.woff2 new file mode 100644 index 0000000..4c46295 Binary files /dev/null and b/public/fonts/geist-cyrillic-ext.woff2 differ diff --git a/public/fonts/geist-cyrillic.woff2 b/public/fonts/geist-cyrillic.woff2 new file mode 100644 index 0000000..4b7a2be Binary files /dev/null and b/public/fonts/geist-cyrillic.woff2 differ diff --git a/public/fonts/geist-latin-ext.woff2 b/public/fonts/geist-latin-ext.woff2 new file mode 100644 index 0000000..ba90e20 Binary files /dev/null and b/public/fonts/geist-latin-ext.woff2 differ diff --git a/public/fonts/geist-latin.woff2 b/public/fonts/geist-latin.woff2 new file mode 100644 index 0000000..991445d Binary files /dev/null and b/public/fonts/geist-latin.woff2 differ diff --git a/public/fonts/geist-vietnamese.woff2 b/public/fonts/geist-vietnamese.woff2 new file mode 100644 index 0000000..ee96589 Binary files /dev/null and b/public/fonts/geist-vietnamese.woff2 differ diff --git a/public/site.css b/public/site.css index 3542540..8924494 100644 --- a/public/site.css +++ b/public/site.css @@ -1,3 +1,50 @@ +/* Geist is served from this site so the tools keep their font offline and no page talks to Google. License: /fonts/OFL.txt */ + +@font-face { + font-family: "Geist"; + font-style: normal; + font-weight: 400 700; + font-display: swap; + src: url(/fonts/geist-cyrillic-ext.woff2) format("woff2"); + unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} + +@font-face { + font-family: "Geist"; + font-style: normal; + font-weight: 400 700; + font-display: swap; + src: url(/fonts/geist-cyrillic.woff2) format("woff2"); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} + +@font-face { + font-family: "Geist"; + font-style: normal; + font-weight: 400 700; + font-display: swap; + src: url(/fonts/geist-vietnamese.woff2) format("woff2"); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; +} + +@font-face { + font-family: "Geist"; + font-style: normal; + font-weight: 400 700; + font-display: swap; + src: url(/fonts/geist-latin-ext.woff2) format("woff2"); + unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF; +} + +@font-face { + font-family: "Geist"; + font-style: normal; + font-weight: 400 700; + font-display: swap; + src: url(/fonts/geist-latin.woff2) format("woff2"); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} + /* tools.halit.org components. Tokens come from tokens.css, which the build puts in front of this file. */ .sr-only { @@ -205,6 +252,71 @@ ol { background: var(--muted); } +/* install button, shown by nav.js only where the browser can install the site */ +.install { + position: relative; +} + +.install[hidden], +.install-hint[hidden] { + display: none; +} + +.install-btn { + display: inline-flex; + align-items: center; + gap: 6px; + height: var(--nav-h); + padding: 0; + border: 0; + background: none; + font: inherit; + color: var(--muted-foreground); + white-space: nowrap; + cursor: pointer; + transition: color var(--fast) var(--ease); +} + +.install-btn:hover, +.install-btn[aria-expanded="true"] { + color: var(--foreground); +} + +.install-icon { + flex: none; + width: 18px; + height: 18px; +} + +.install-short { + display: none; +} + +.install-hint { + position: absolute; + top: calc(100% - 8px); + right: 0; + z-index: 20; + width: 248px; + padding: 12px 14px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--background); + box-shadow: 0 4px 16px rgb(0 0 0 / 0.08); + color: var(--foreground); + font-size: 14px; + font-weight: 400; + line-height: 1.5; + white-space: normal; +} + +.share-icon { + display: inline-block; + width: 18px; + height: 18px; + vertical-align: -4px; +} + /* the hairline keeps the white parts of a flag visible on the white menu */ .flag { flex: none; @@ -2203,6 +2315,31 @@ code { display: inline; } + .install { + position: static; + } + + .install-long { + display: none; + } + + .install-short { + display: inline; + } + + .install-hint { + top: 100%; + left: 0; + right: 0; + width: auto; + padding: 12px var(--gutter) 16px; + border: 0; + border-bottom: 1px solid var(--border); + border-radius: 0; + box-shadow: 0 8px 16px rgb(0 0 0 / 0.06); + font-size: 16px; + } + .lang-list { top: 100%; left: 0; @@ -2267,6 +2404,18 @@ code { } } +/* below 380px the label would squeeze the signature, so the icon stands alone with a full-size tap target */ +@media (max-width: 380px) { + .install-short { + display: none; + } + + .install-btn { + justify-content: center; + min-width: 44px; + } +} + @media (prefers-reduced-motion: reduce) { *, *::before, diff --git a/scripts/browser-check.mjs b/scripts/browser-check.mjs index c7417fd..536f8e2 100644 --- a/scripts/browser-check.mjs +++ b/scripts/browser-check.mjs @@ -11,7 +11,7 @@ const root = fileURLToPath(new URL("../_site/", import.meta.url)); const shots = process.argv[2] ?? "shots"; const pw = process.env.PLAYWRIGHT_CORE ?? `${process.env.HOME}/.cache/seo-cdp/node_modules/playwright-core/index.mjs`; const { chromium } = await import(pathToFileURL(pw).href); -const TYPES = { ".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "text/javascript", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", ".xml": "application/xml", ".txt": "text/plain", ".webmanifest": "application/manifest+json" }; +const TYPES = { ".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "text/javascript", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", ".xml": "application/xml", ".txt": "text/plain", ".webmanifest": "application/manifest+json", ".woff2": "font/woff2" }; const server = createServer(async (req, res) => { let path = normalize(decodeURIComponent(new URL(req.url, "http://x").pathname)); diff --git a/scripts/build.mjs b/scripts/build.mjs index 9ae8a7f..a86669e 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -1,5 +1,5 @@ -/** Builds tools.halit.org into _site/: static HTML per page and language, sitemap, robots.txt and llms.txt. */ -import { mkdir, writeFile, cp, readFile, rm } from "node:fs/promises"; +/** Builds tools.halit.org into _site/: static HTML per page and language, sitemap, robots.txt, llms.txt, web manifests and the service worker. */ +import { mkdir, writeFile, cp, readFile, readdir, rm } from "node:fs/promises"; import { createHash } from "node:crypto"; import { transform } from "esbuild"; import { pages, TOOLS, SITE } from "./content.mjs"; @@ -23,10 +23,11 @@ const INTRO_HASH = createHash("sha256").update(INTRO).digest("base64"); const CSP = [ "default-src 'none'", `script-src 'self' 'sha256-${INTRO_HASH}' https://static.cloudflareinsights.com`, - "style-src 'self' https://fonts.googleapis.com", - "font-src https://fonts.gstatic.com", + "style-src 'self'", + "font-src 'self'", "img-src 'self'", "manifest-src 'self'", + "worker-src 'self'", "connect-src https://cloudflareinsights.com", "base-uri 'none'", "form-action 'none'", @@ -46,6 +47,8 @@ const LANGS = [ ["en", "English"], ["tr", "Türkçe"], ]; +const DOWNLOAD = ``; +const SHARE = ``; const CHECK = ``; function check(page) { @@ -78,7 +81,8 @@ ${alt} - + + @@ -94,12 +98,10 @@ ${alt} - - - - + + ${ld.join("\n")} - + `; } @@ -114,12 +116,19 @@ function langMenu(page) { return `

`; } +/** Hidden until nav.js learns the browser can install the site, or that it is iOS, where the hint replaces a prompt. */ +function installButton(page) { + const s = SITE[page.lang]; + const [before, after] = s.iosHint; + return ``; +} + function topbar(page) { const s = SITE[page.lang]; return `
- +
`; } @@ -769,7 +778,7 @@ ${sections.map((sec) => infoSection(page, sec)).join("\n")} `, ` -`, +`, ); } @@ -837,26 +846,62 @@ function minifyCss(css) { .trim(); } -const manifest = { - name: "Halit Sever's tools", - short_name: "Tools", - start_url: "/", - display: "browser", - background_color: "#ffffff", - theme_color: "#ffffff", - icons: [ - { src: "/icons/icon-192x192.png", sizes: "192x192", type: "image/png" }, - { src: "/icons/icon-512x512.png", sizes: "512x512", type: "image/png" }, - { src: "/icons/icon-maskable-512x512.png", sizes: "512x512", type: "image/png", purpose: "maskable" }, - ], +const MANIFEST = { en: "/site.webmanifest", tr: "/tr/site.webmanifest" }; +const FONTS = (await readdir(new URL("../public/fonts/", import.meta.url))).filter((f) => f.endsWith(".woff2")).map((f) => `/fonts/${f}`); +const ICONS = ["/icons/icon-192x192.png", "/icons/icon-512x512.png", "/icons/icon-maskable-512x512.png"]; + +/** One app per language: the id keeps a Turkish install opening at /tr/ and stops the two manifests from overwriting each other. */ +function manifest(lang) { + const s = SITE[lang]; + const home = pages.list.find((p) => p.kind === "index" && p.lang === lang); + const shortcuts = TOOLS.map((t) => t[lang]) + .filter((t) => !t.lang || t.lang === lang) + .slice(0, 4) + .map((t) => ({ name: t.name, url: t.path })); + return { + id: s.home, + name: s.name, + short_name: s.short, + description: home.description, + lang, + dir: "ltr", + start_url: s.home, + scope: "/", + display: "standalone", + background_color: "#ffffff", + theme_color: "#ffffff", + categories: ["utilities", "productivity"], + icons: [ + { src: ICONS[0], sizes: "192x192", type: "image/png" }, + { src: ICONS[1], sizes: "512x512", type: "image/png" }, + { src: ICONS[2], sizes: "512x512", type: "image/png", purpose: "maskable" }, + ], + shortcuts, + }; +} + +const SCRIPTS = ["clean.js", "plain-text.js", "diff.js", "text-compare.js", "kdv.js", "kdv-hesaplama.js", "yas.js", "yas-hesaplama.js", "date-diff.js", "days-between-dates.js", "line-breaks.js", "remove-line-breaks.js", "case.js", "case-converter.js", "color.js", "hex-to-rgb.js", "invisible.js", "invisible-character.js", "repeat.js", "text-repeater.js", "reverse.js", "reverse-text.js", "flip.js", "upside-down-text.js", "chmod.js", "chmod-calculator.js", "slug.js", "slug-generator.js", "special.js", "remove-special-characters.js", "count.js", "karakter-sayaci.js", "frequency.js", "word-frequency-counter.js", "nav.js"]; +const sha = (...parts) => { + const h = createHash("sha256"); + for (const p of parts) h.update(p); + return h.digest("hex").slice(0, 12); }; +const css = minifyCss((await read("../tokens.css")) + "\n" + (await read("../public/site.css"))); +const scripts = {}; +for (const f of SCRIPTS) scripts[f] = (await transform(await read(`../src/${f}`), { minify: true, format: "esm", target: "es2022" })).code; + +/** Asset URLs carry this hash, so a service worker from the previous deploy can never answer them from its cache. */ +const ASSET_V = sha(css, ...SCRIPTS.map((f) => f + scripts[f])); +const asset = (f) => `/${f}?v=${ASSET_V}`; +const versionImports = (code) => code.replace(/(from|import)\s*"\.\/([\w-]+\.js)"/g, (_, kw, f) => `${kw}"${asset(f)}"`); + await rm(OUT, { recursive: true, force: true }); await mkdir(OUT, { recursive: true }); await cp(new URL("../public/", import.meta.url), OUT, { recursive: true }); await rm(new URL("signature.svg", OUT)); -await writeFile(new URL("site.css", OUT), minifyCss((await read("../tokens.css")) + "\n" + (await read("../public/site.css")))); -for (const f of ["clean.js", "plain-text.js", "diff.js", "text-compare.js", "kdv.js", "kdv-hesaplama.js", "yas.js", "yas-hesaplama.js", "date-diff.js", "days-between-dates.js", "line-breaks.js", "remove-line-breaks.js", "case.js", "case-converter.js", "color.js", "hex-to-rgb.js", "invisible.js", "invisible-character.js", "repeat.js", "text-repeater.js", "reverse.js", "reverse-text.js", "flip.js", "upside-down-text.js", "chmod.js", "chmod-calculator.js", "slug.js", "slug-generator.js", "special.js", "remove-special-characters.js", "count.js", "karakter-sayaci.js", "frequency.js", "word-frequency-counter.js", "nav.js"]) await writeFile(new URL(f, OUT), (await transform(await read(`../src/${f}`), { minify: true, format: "esm", target: "es2022" })).code); +await writeFile(new URL("site.css", OUT), css); +for (const f of SCRIPTS) await writeFile(new URL(f, OUT), versionImports(scripts[f])); const built = []; for (const page of pages.list) { @@ -870,6 +915,16 @@ await writeFile(new URL("404.html", OUT), notFound()); await writeFile(new URL("sitemap.xml", OUT), sitemap(built)); await writeFile(new URL("robots.txt", OUT), `User-agent: *\nAllow: /\n\nSitemap: ${ORIGIN}/sitemap.xml\n`); await writeFile(new URL("llms.txt", OUT), llms()); -await writeFile(new URL("site.webmanifest", OUT), JSON.stringify(manifest, null, 2) + "\n"); +for (const lang of ["en", "tr"]) await writeFile(new URL(`.${MANIFEST[lang]}`, OUT), JSON.stringify(manifest(lang), null, 2) + "\n"); + +/** Everything a tool needs offline. The cache name hashes these files, so any change to them installs a new worker. */ +const PRECACHE = [...built.map((p) => p.path), "/site.css", ...SCRIPTS, ...Object.values(MANIFEST), ...ICONS, ...FONTS, "/favicon.ico", "/favicon.svg", "/apple-touch-icon.png"].map((u) => + u.endsWith(".css") || u.endsWith(".js") ? asset(u.replace(/^\//, "")) : u, +); +const files = await Promise.all(PRECACHE.map((u) => readFile(new URL(`.${u.replace(/\?.*$/, "").replace(/\/$/, "/index.html")}`, OUT)))); +const BUILD = sha(...PRECACHE, ...files); +const sw = (await read("../src/sw.js")).replace('const BUILD = "dev";', () => `const BUILD = ${JSON.stringify(BUILD)};`).replace("const PRECACHE = [];", () => `const PRECACHE = ${JSON.stringify(PRECACHE)};`); +if (!sw.includes(BUILD) || sw.includes("const PRECACHE = [];")) throw new Error("sw.js placeholders not found"); +await writeFile(new URL("sw.js", OUT), (await transform(sw, { minify: true, target: "es2022" })).code); await writeFile(new URL(".nojekyll", OUT), ""); -console.log(`${built.length} pages, ${TOOLS.length} tool(s), 404, sitemap, robots.txt, llms.txt`); +console.log(`${built.length} pages, ${TOOLS.length} tool(s), 404, sitemap, robots.txt, llms.txt, sw.js ${BUILD} (${PRECACHE.length} files)`); diff --git a/scripts/content.mjs b/scripts/content.mjs index 784fbc8..3ed0eac 100644 --- a/scripts/content.mjs +++ b/scripts/content.mjs @@ -37,6 +37,9 @@ export const SITE = { name: "Halit Sever's tools", short: "Tools", home: "/", + install: "Install app", + installShort: "Install", + iosHint: ["Tap Share", ", then Add to Home Screen."], navLabel: "Site", footLabel: "Footer", projects: "Projects", @@ -50,7 +53,7 @@ export const SITE = { count: (n) => (n === 1 ? "1 tool so far" : `${n} tools`), howTitle: "How these tools work", how: [ - "Every tool here is plain JavaScript that runs in the page you have open. What you paste or type is processed in this tab and is never uploaded or saved on a server, and you need no account. Once a page has loaded, its tool keeps working even if your connection drops. Nothing runs on a server: the site is static HTML, CSS and JavaScript served by GitHub Pages.", + "Every tool here is plain JavaScript that runs in the page you have open. What you paste or type is processed in this tab and is never uploaded or saved on a server, and you need no account. After your first visit every tool works offline too, and Chrome, Edge or Safari can install the site as an app on your computer or phone. Nothing runs on a server: the site is static HTML, CSS and JavaScript served by GitHub Pages.", "Each page ships a Content-Security-Policy that makes the browser block connections to every server except Cloudflare Web Analytics, which counts page views and never sees your text. Settings such as the paste options are remembered in your own browser only.", `The code is open source on ${a(REPO, "GitHub")}, so you can read exactly what each tool does or build the site yourself.`, ], @@ -59,6 +62,9 @@ export const SITE = { name: "Halit Sever'in araçları", short: "Araçlar", home: "/tr/", + install: "Uygulamayı yükle", + installShort: "Yükle", + iosHint: ["Paylaş", " simgesine, ardından Ana Ekrana Ekle'ye dokun."], navLabel: "Site", footLabel: "Alt bilgi", projects: "Projeler", @@ -72,7 +78,7 @@ export const SITE = { count: (n) => (n === 1 ? "Şimdilik 1 araç" : `${n} araç`), howTitle: "Bu araçlar nasıl çalışır?", how: [ - "Buradaki her araç, açtığın sayfanın içinde çalışan sade bir JavaScript. Yapıştırdığın ya da yazdığın metin bu sekmede işlenir; hiçbir sunucuya yüklenmez, bir yerde saklanmaz. Hesap açman da gerekmez. Sayfa bir kez yüklendikten sonra bağlantın kopsa bile araç çalışmaya devam eder. Sunucuda çalışan bir kod yok: site, GitHub Pages'in sunduğu statik HTML, CSS ve JavaScript dosyalarından oluşuyor.", + "Buradaki her araç, açtığın sayfanın içinde çalışan sade bir JavaScript. Yapıştırdığın ya da yazdığın metin bu sekmede işlenir; hiçbir sunucuya yüklenmez, bir yerde saklanmaz. Hesap açman da gerekmez. İlk ziyaretten sonra bütün araçlar internet olmadan da çalışır; Chrome, Edge ya da Safari ile siteyi bilgisayarına veya telefonuna uygulama olarak yükleyebilirsin. Sunucuda çalışan bir kod yok: site, GitHub Pages'in sunduğu statik HTML, CSS ve JavaScript dosyalarından oluşuyor.", "Her sayfa bir Content-Security-Policy ile gelir. Bu kural, Cloudflare Web Analytics dışındaki bütün sunuculara bağlantıyı tarayıcıya engelletir; Cloudflare yalnızca sayfa görüntülemelerini sayar, metnini görmez. Yapıştırma seçenekleri gibi ayarlar sadece senin tarayıcında kalır.", `Kod ${a(REPO, "GitHub'da")} açık kaynak. Her aracın tam olarak ne yaptığını okuyabilir, siteyi kendin de derleyebilirsin.`, ], diff --git a/scripts/pwa-check.mjs b/scripts/pwa-check.mjs new file mode 100644 index 0000000..47b11fc --- /dev/null +++ b/scripts/pwa-check.mjs @@ -0,0 +1,210 @@ +/** + * Local check of the installable app in _site/: manifests, service worker, offline pages, cache turnover, install button. + * Lighter than browser-check.mjs. Same env: PLAYWRIGHT_CORE= CHROME= node scripts/pwa-check.mjs [shots dir] + */ +import { createServer } from "node:http"; +import { readFile, mkdir, mkdtemp, rm } from "node:fs/promises"; +import { extname, join, normalize } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const root = fileURLToPath(new URL("../_site/", import.meta.url)); +const shots = process.argv[2] ?? "shots"; +const pw = process.env.PLAYWRIGHT_CORE ?? `${process.env.HOME}/.cache/seo-cdp/node_modules/playwright-core/index.mjs`; +const { chromium } = await import(pathToFileURL(pw).href); +const TYPES = { ".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "text/javascript", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", ".webmanifest": "application/manifest+json", ".woff2": "font/woff2" }; + +/** `down` drops every connection like a lost network; `deploy` serves a changed sw.js and page, as after a new build. */ +const state = { down: false, deploy: false }; +const server = createServer(async (req, res) => { + if (state.down) return req.socket.destroy(); + let path = normalize(decodeURIComponent(new URL(req.url, "http://x").pathname)); + if (path.endsWith("/")) path += "index.html"; + try { + let body = await readFile(join(root, path)); + if (state.deploy && path === "/sw.js") body = String(body).replace(/BUILD="(\w+)"/, 'BUILD="$1next"'); + if (state.deploy && path === "/text-compare/index.html") body = String(body).replace("new

server.once("listening", r)); +const base = `http://127.0.0.1:${server.address().port}`; + +const browser = await chromium.launch({ executablePath: process.env.CHROME ?? "/usr/bin/google-chrome", headless: true }); +await mkdir(shots, { recursive: true }); +const failures = []; +const expect = (cond, msg) => { + if (!cond) failures.push(msg); +}; + +const sw = String(await readFile(join(root, "sw.js"))); +const PRECACHE = JSON.parse(sw.match(/PRECACHE=(\[[^\]]*\])/)[1]); +const PAGES = PRECACHE.filter((u) => u.endsWith("/")); + +async function context(width, ua) { + const ctx = await browser.newContext({ viewport: { width, height: width > 500 ? 900 : 844 }, deviceScaleFactor: width > 500 ? 1 : 2, userAgent: ua }); + await ctx.route("https://static.cloudflareinsights.com/**", (r) => r.fulfill({ status: 200, contentType: "text/javascript", body: "" })); + const page = await ctx.newPage(); + const errors = []; + await page.exposeFunction("__cspReport", (v) => errors.push(`CSP ${v}`)); + await page.addInitScript(() => document.addEventListener("securitypolicyviolation", (e) => window.__cspReport(`${e.violatedDirective} ${e.blockedURI}`))); + page.on("console", (m) => m.type() === "error" && errors.push(`${page.url()}: ${m.text()}`)); + page.on("pageerror", (e) => errors.push(`${page.url()}: ${e.message}`)); + return { ctx, page, errors }; +} + +const controlled = (page) => page.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { timeout: 15000 }); + +// Manifests: linked on every page, valid, with what Chrome needs to install. +for (const path of [...PAGES, "/404.html"]) { + const html = String(await readFile(join(root, path.endsWith("/") ? `${path}index.html` : path))); + const tr = path.startsWith("/tr/"); + expect(html.includes(``), `${path}: manifest link`); + expect(html.includes('name="apple-mobile-web-app-title"') && html.includes('rel="apple-touch-icon"') && html.includes('name="theme-color"'), `${path}: apple meta`); + expect(html.includes("worker-src 'self'"), `${path}: CSP worker-src`); +} +for (const [file, lang, start] of [["site.webmanifest", "en", "/"], ["tr/site.webmanifest", "tr", "/tr/"]]) { + const m = JSON.parse(await readFile(join(root, file), "utf8")); + expect(m.display === "standalone" && m.scope === "/" && m.start_url === start && m.id === start && m.lang === lang, `${file}: display, scope, start or id`); + expect(m.name && m.short_name && m.short_name.length <= 12 && /^#[0-9a-f]{6}$/.test(m.theme_color) && /^#[0-9a-f]{6}$/.test(m.background_color), `${file}: names or colours`); + expect(["192x192", "512x512"].every((s) => m.icons.some((i) => i.sizes === s && i.type === "image/png" && !i.purpose)) && m.icons.some((i) => i.purpose === "maskable"), `${file}: icons`); + for (const i of m.icons) expect(PRECACHE.includes(i.src), `${file}: icon ${i.src} not precached`); + expect(m.shortcuts.length >= 2 && m.shortcuts.every((s) => s.name && PAGES.includes(s.url) && s.url.startsWith(lang === "tr" ? "/tr/" : "/") && (lang === "tr" || !s.url.startsWith("/tr/"))), `${file}: shortcuts`); +} + +// Chrome's own installability verdict and manifest parse, then the service worker and offline use of every page. +{ + const { ctx, page, errors } = await context(1280); + for (const [path, manifest] of [["/", "/site.webmanifest"], ["/tr/", "/tr/site.webmanifest"]]) { + await page.goto(base + path, { waitUntil: "load" }); + await controlled(page); + const cdp = await ctx.newCDPSession(page); + const parsed = await cdp.send("Page.getAppManifest"); + expect(parsed.url.endsWith(manifest) && parsed.errors.length === 0, `${path}: manifest errors ${JSON.stringify(parsed.errors)}`); + await cdp.detach(); + } + const scope = await page.evaluate(async () => (await navigator.serviceWorker.getRegistration()).scope); + expect(scope === `${base}/`, `service worker scope ${scope}`); + const keys = await page.evaluate(() => caches.keys()); + const cached = await page.evaluate(async (k) => (await (await caches.open(k)).keys()).map((r) => new URL(r.url).pathname + new URL(r.url).search), keys[0]); + expect(keys.length === 1 && PRECACHE.every((u) => cached.includes(u)), `precache incomplete: ${PRECACHE.filter((u) => !cached.includes(u)).join(" ")}`); + + state.down = true; + await ctx.setOffline(true); + for (const path of PAGES) { + await page.goto(base + path, { waitUntil: "load" }); + const ok = await page.evaluate(async () => { + await document.fonts.ready; + return { h1: document.querySelector("h1")?.textContent ?? "", css: getComputedStyle(document.querySelector(".bar")).position, tool: !!document.querySelector(".tool, .tools-list"), font: [...document.fonts].some((f) => f.family === "Geist" && f.status === "loaded") }; + }); + expect(ok.h1 && ok.css === "sticky" && ok.tool && ok.font, `${path}: offline page broken ${JSON.stringify(ok)}`); + } + await page.goto(`${base}/text-compare/`, { waitUntil: "load" }); + await page.fill("#a", "Ship on Friday"); + await page.fill("#b", "Ship on Monday"); + await page.waitForTimeout(400); + expect((await page.locator("#result ins").allTextContents()).join("|") === "Monday", "text compare does not run offline"); + await page.goto(`${base}/tr/kdv-hesaplama/`, { waitUntil: "load" }); + await page.screenshot({ path: `${shots}/pwa-offline-kdv-1280.png` }); + await page.goto(`${base}/tr/missing`, { waitUntil: "load" }); + expect((await page.evaluate(() => location.pathname)) === "/tr/missing" && (await page.locator(".tools-list").count()) === 1, "offline unknown TR page does not fall back to /tr/"); + await page.reload({ waitUntil: "load" }); + expect((await page.locator(".tools-list").count()) === 1, "offline reload failed"); + await ctx.setOffline(false); + state.down = false; + + // Network first: a changed page shows at once, and a new worker replaces the old cache. + state.deploy = true; + await page.goto(`${base}/text-compare/`, { waitUntil: "load" }); + expect((await page.locator("#deployed").count()) === 1, "changed page hidden behind the cache"); + await page.evaluate(() => navigator.serviceWorker.getRegistration().then((r) => r.update())); + let after = []; + for (let i = 0; i < 80 && !(after.length === 1 && after[0] !== keys[0]); i++) { + await page.waitForTimeout(250); + after = await page.evaluate(() => caches.keys()); + } + expect(after.length === 1 && after[0] === `${keys[0]}next`, `cache after deploy ${after}`); + state.deploy = false; + expect(errors.length === 0, `console or CSP errors: ${errors.join(" | ")}`); + await ctx.close(); +} + +// Chrome refuses to install from incognito, which every newContext is, so this verdict needs a profile on disk. +{ + const dir = await mkdtemp(join(process.env.PWA_PROFILE_DIR ?? fileURLToPath(new URL("../", import.meta.url)), ".pwa-profile-")); + const ctx = await chromium.launchPersistentContext(dir, { executablePath: process.env.CHROME ?? "/usr/bin/google-chrome", headless: true }); + const page = ctx.pages()[0] ?? (await ctx.newPage()); + for (const path of ["/", "/tr/"]) { + await page.goto(base + path, { waitUntil: "load" }); + await controlled(page); + const cdp = await ctx.newCDPSession(page); + const { installabilityErrors } = await cdp.send("Page.getInstallabilityErrors"); + expect(installabilityErrors.length === 0, `${path}: installability ${JSON.stringify(installabilityErrors)}`); + await cdp.detach(); + } + await ctx.close(); + await rm(dir, { recursive: true, force: true }); +} + +// Install button: hidden until the browser offers a prompt, used once, never shown in the installed app. +const fakePrompt = () => { + const e = new Event("beforeinstallprompt", { cancelable: true }); + e.prompt = () => ((window.__prompted = true), Promise.resolve({ outcome: "accepted" })); + window.dispatchEvent(e); +}; +for (const [lang, path] of [["en", "/text-compare/"], ["tr", "/tr/kdv-hesaplama/"]]) { + for (const width of [1280, 390]) { + const label = `${lang} install ${width}`; + const { ctx, page, errors } = await context(width); + await page.goto(base + path, { waitUntil: "load" }); + const btn = page.locator(".install-btn"); + expect(!(await btn.isVisible()), `${label}: visible before any prompt`); + await page.evaluate(fakePrompt); + expect(await btn.isVisible(), `${label}: not shown after beforeinstallprompt`); + const box = await page.locator(".bar-in").boundingBox(); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth); + expect(overflow <= 0 && box.height <= 57, `${label}: bar overflows`); + await page.screenshot({ path: `${shots}/pwa-install-${lang}-${width}.png` }); + await btn.click(); + expect((await page.evaluate(() => window.__prompted)) && !(await btn.isVisible()), `${label}: prompt not used or button still shown`); + expect(errors.length === 0, `${label}: errors ${errors.join(" | ")}`); + await ctx.close(); + } +} +{ + const { ctx, page } = await context(1280); + await page.addInitScript(() => { + const mm = window.matchMedia.bind(window); + window.matchMedia = (q) => (q.includes("display-mode: standalone") ? { matches: true, media: q, addEventListener() {} } : mm(q)); + }); + await page.goto(`${base}/`, { waitUntil: "load" }); + await page.evaluate(fakePrompt); + expect(!(await page.locator(".install-btn").isVisible()), "install button shown in standalone mode"); + await ctx.close(); +} +const IPHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1"; +for (const [lang, path] of [["en", "/"], ["tr", "/tr/"]]) { + const { ctx, page, errors } = await context(390, IPHONE); + await page.goto(base + path, { waitUntil: "load" }); + const btn = page.locator(".install-btn"); + expect(await btn.isVisible(), `${lang} iOS: button hidden`); + await btn.click(); + const hint = page.locator(".install-hint"); + expect((await hint.isVisible()) && (await hint.locator("svg").count()) === 1, `${lang} iOS: hint not shown`); + await page.screenshot({ path: `${shots}/pwa-ios-hint-${lang}-390.png` }); + await page.keyboard.press("Escape"); + expect(!(await hint.isVisible()), `${lang} iOS: Escape did not close the hint`); + expect(errors.length === 0, `${lang} iOS: errors ${errors.join(" | ")}`); + await ctx.close(); +} + +await browser.close(); +server.close(); +if (failures.length) { + console.error(failures.join("\n")); + process.exit(1); +} +console.log(`pwa check passed: ${PAGES.length} pages offline, screenshots in ${shots}/`); diff --git a/src/nav.js b/src/nav.js index dc0009f..0709fe8 100644 --- a/src/nav.js +++ b/src/nav.js @@ -1,4 +1,4 @@ -/** Language menu in the top bar. A file of its own because the CSP allows no inline handlers. */ +/** Top bar menus, the install button and the service worker. A file of its own because the CSP allows no inline handlers. */ const root = document.querySelector("[data-lang-menu]"); if (root) { @@ -29,3 +29,58 @@ if (root) { /** Back and forward can restore the page from the bfcache with the menu still open. */ window.addEventListener("pageshow", () => setOpen(false)); } + +/** Install button: Chrome and Edge hand over their prompt, iOS has none, so it gets a hint instead. */ +const install = document.querySelector("[data-install]"); +const standalone = matchMedia("(display-mode: standalone)").matches || navigator.standalone === true; + +if (install && !standalone) { + const button = install.querySelector("button"); + const hint = install.querySelector(".install-hint"); + const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1); + let prompt = null; + + const setHint = (open) => { + button.setAttribute("aria-expanded", String(open)); + hint.hidden = !open; + }; + + if (ios) { + button.setAttribute("aria-controls", hint.id); + setHint(false); + install.hidden = false; + document.addEventListener("click", (event) => { + if (!hint.hidden && !install.contains(event.target)) setHint(false); + }); + document.addEventListener("keydown", (event) => { + if (event.key === "Escape" && !hint.hidden) setHint(false); + }); + } + + window.addEventListener("beforeinstallprompt", (event) => { + event.preventDefault(); + prompt = event; + install.hidden = false; + }); + + window.addEventListener("appinstalled", () => { + prompt = null; + install.hidden = true; + }); + + button.addEventListener("click", async () => { + if (!prompt) { + if (ios) setHint(hint.hidden); + return; + } + const event = prompt; + prompt = null; + // A prompt can be shown once; Chrome fires a fresh event if it may ask again. + install.hidden = true; + await event.prompt(); + }); +} + +if ("serviceWorker" in navigator) { + window.addEventListener("load", () => navigator.serviceWorker.register("/sw.js").catch(() => {})); +} diff --git a/src/sw.js b/src/sw.js new file mode 100644 index 0000000..928a0e0 --- /dev/null +++ b/src/sw.js @@ -0,0 +1,44 @@ +/** Offline support for tools.halit.org. The build fills in BUILD and PRECACHE; pages are network first so a deploy is never hidden behind the cache. */ +const BUILD = "dev"; +const PRECACHE = []; +const CACHE = `tools-${BUILD}`; + +self.addEventListener("install", (event) => { + // cache: "reload" skips the HTTP cache, which could still hold files from the previous deploy. + event.waitUntil( + caches + .open(CACHE) + .then((cache) => cache.addAll(PRECACHE.map((url) => new Request(url, { cache: "reload" })))) + .then(() => self.skipWaiting()), + ); +}); + +self.addEventListener("activate", (event) => { + event.waitUntil( + caches + .keys() + .then((keys) => Promise.all(keys.filter((key) => key.startsWith("tools-") && key !== CACHE).map((key) => caches.delete(key)))) + .then(() => self.clients.claim()), + ); +}); + +/** Offline fallback for a page: the cached copy, else the home page of its language. */ +async function cachedPage(url) { + const cache = await caches.open(CACHE); + const path = url.pathname.endsWith("/") || url.pathname.endsWith(".html") ? url.pathname : `${url.pathname}/`; + return (await cache.match(path)) ?? (await cache.match(path.startsWith("/tr/") ? "/tr/" : "/")) ?? Response.error(); +} + +self.addEventListener("fetch", (event) => { + const { request } = event; + const url = new URL(request.url); + // Cross-origin requests (fonts, the analytics beacon) go straight to the network under the page's own CSP. + if (request.method !== "GET" || url.origin !== self.location.origin) return; + + if (request.mode === "navigate") { + event.respondWith(fetch(request).catch(() => cachedPage(url))); + return; + } + + event.respondWith(caches.open(CACHE).then((cache) => cache.match(request)).then((hit) => hit ?? fetch(request))); +});