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

refactor(route/caniuse): merge respec-caniuse-route to main #146

Merged
merged 2 commits into from
Feb 18, 2021
Merged
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
52 changes: 47 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
"helmet": "^4.1.0",
"morgan": "^1.10.0",
"node-fetch": "^2.6.1",
"respec-caniuse-route": "^3.1.1",
"respec-github-apis": "^2.0.0",
"respec-xref-route": "^9.0.4",
"split2": "^3.2.2",
"ucontent": "^2.0.0"
},
"scripts": {
Expand All @@ -39,6 +39,7 @@
"@types/express": "^4.17.11",
"@types/node": "^14.14.25",
"@types/node-fetch": "^2.5.8",
"@types/split2": "^2.1.6",
"typescript": "^4.1.3"
}
}
2 changes: 1 addition & 1 deletion routes/caniuse/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import cors from "cors";
import authGithubWebhook from "../../utils/auth-github-webhook.js";
import { env, seconds } from "../../utils/misc.js";

import { createResponseBody } from "respec-caniuse-route";
import { createResponseBody } from "./lib/index.js";
import updateRoute from "./update.js";

const caniuse = Router({ mergeParams: true });
Expand Down
1 change: 1 addition & 0 deletions routes/caniuse/lib/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
This directory was originally maintained in a separate repository at https://github.com/sidvishnoi/respec-caniuse-route.
28 changes: 28 additions & 0 deletions routes/caniuse/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export const BROWSERS = new Map([
['and_chr', 'Chrome (Android)'],
['and_ff', 'Firefox (Android)'],
['and_uc', 'UC Browser (Android)'],
['android', 'Android'],
['bb', 'Blackberry'],
['chrome', 'Chrome'],
['edge', 'Edge'],
['firefox', 'Firefox'],
['ie', 'IE'],
['ios_saf', 'Safari (iOS)'],
['op_mini', 'Opera Mini'],
['op_mob', 'Opera Mobile'],
['opera', 'Opera'],
['safari', 'Safari'],
['samsung', 'Samsung Internet'],
]);

// Keys from https://github.com/Fyrd/caniuse/blob/master/CONTRIBUTING.md
export const SUPPORT_TITLES = new Map([
['y', 'Supported.'],
['a', 'Almost supported (aka Partial support).'],
['n', 'No support, or disabled by default.'],
['p', 'No support, but has Polyfill.'],
['u', 'Support unknown.'],
['x', 'Requires prefix to work.'],
['d', 'Disabled by default (needs to enabled).'],
]);
159 changes: 159 additions & 0 deletions routes/caniuse/lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import * as path from "path";
import { promises as fs } from "fs";

import { html } from "ucontent";

import { BROWSERS, SUPPORT_TITLES } from "./constants.js";
import { env } from "../../../utils/misc.js";
import { MemCache } from "../../../utils/mem-cache.js";

const DATA_DIR = env("DATA_DIR");

interface Options {
feature: string;
browsers?: string[];
versions?: number;
format?: "html" | "json";
}
type NormalizedOptions = Required<Options>;

type SupportKeys = ("y" | "n" | "a" | string)[];
// [ version, ['y', 'n'] ]
type BrowserVersionData = [string, SupportKeys];

interface Data {
[browserName: string]: BrowserVersionData[];
}

const defaultOptions = {
browsers: ["chrome", "firefox", "safari", "edge"],
versions: 4,
};

// Content in this cache is invalidated through `POST /caniuse/update`.
export const cache = new MemCache<Data>(Infinity);

export async function createResponseBody(options: Options) {
const opts = normalizeOptions(options);

switch (opts.format) {
case "json":
return await createResponseBodyJSON(opts);
case "html":
default:
return await createResponseBodyHTML(opts);
}
}

export async function createResponseBodyJSON(options: NormalizedOptions) {
const { feature, browsers, versions } = options;
const data = await getData(feature);
if (!data) {
return null;
}

if (!browsers.length) {
browsers.push(...Object.keys(data));
}

const response: Data = Object.create(null);
for (const browser of browsers) {
const browserData = data[browser] || [];
response[browser] = browserData.slice(0, versions);
}
return response;
}

export async function createResponseBodyHTML(options: NormalizedOptions) {
const data = await createResponseBodyJSON(options);
return data === null ? null : formatAsHTML(options, data);
}

function normalizeOptions(options: Options): NormalizedOptions {
const feature = options.feature;
const versions = options.versions || defaultOptions.versions;
const browsers = sanitizeBrowsersList(options.browsers);
const format = options.format === "html" ? "html" : "json";
return { feature, versions, browsers, format };
}

function sanitizeBrowsersList(browsers?: string | string[]) {
if (!Array.isArray(browsers)) {
if (browsers === "all") return [];
return defaultOptions.browsers;
}
const filtered = browsers.filter(browser => BROWSERS.has(browser));
return filtered.length ? filtered : defaultOptions.browsers;
}

async function getData(feature: string) {
if (cache.has(feature)) {
return cache.get(feature) as Data;
}
const file = path.format({
dir: path.join(DATA_DIR, "caniuse"),
name: `${feature}.json`,
});

try {
const str = await fs.readFile(file, "utf8");
const data: Data = JSON.parse(str);
cache.set(feature, data);
return data;
} catch (error) {
console.error(error);
return null;
}
}

function formatAsHTML(options: NormalizedOptions, data: Data) {
const getSupportTitle = (keys: SupportKeys) => {
return keys
.filter(key => SUPPORT_TITLES.has(key))
.map(key => SUPPORT_TITLES.get(key)!)
.join(" ");
};

const getClassName = (keys: SupportKeys) => `caniuse-cell ${keys.join(" ")}`;

const renderLatestVersion = (
browserName: string,
[version, supportKeys]: BrowserVersionData,
) => {
const text = `${BROWSERS.get(browserName) || browserName} ${version}`;
const className = getClassName(supportKeys);
const title = getSupportTitle(supportKeys);
return html`<button class="${className}" title="${title}">${text}</button>`;
};

const renderOlderVersion = ([version, supportKeys]: BrowserVersionData) => {
const text = version;
const className = getClassName(supportKeys);
const title = getSupportTitle(supportKeys);
return html`<li class="${className}" title="${title}">${text}</li>`;
};

const renderBrowser = (
browser: string,
browserData: BrowserVersionData[],
) => {
const [latestVersion, ...olderVersions] = browserData;
return html`
<div class="caniuse-browser">
${renderLatestVersion(browser, latestVersion)}
<ul>
${olderVersions.map(renderOlderVersion)}
</ul>
</div>
`;
};

const browsers = html`${Object.entries(data).map(([browser, browserData]) =>
renderBrowser(browser, browserData),
)}`;

const featureURL = new URL(options.feature, "https://caniuse.com/").href;
const moreInfo = html`<a href="${featureURL}">More info</a>`;

return html`${browsers} ${moreInfo}`.toString();
}
Loading