Skip to content

Commit

Permalink
Fix some ESLint problems
Browse files Browse the repository at this point in the history
  • Loading branch information
graphemecluster committed Oct 3, 2024
1 parent 9e12d1c commit 1fd7421
Show file tree
Hide file tree
Showing 13 changed files with 62 additions and 60 deletions.
6 changes: 3 additions & 3 deletions src/Classes/CustomElement.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { createElement, Fragment } from "react";
import type { HTMLAttributes, ReactElement } from "react";

import styled from "@emotion/styled";

import type { ReactNode } from "../consts";
import type { Property } from "csstype";
import type { HTMLAttributes, ReactElement } from "react";

const Missing = styled.span`
&:after {
content: "\xa0";
}
`;

type TagToProp = {
interface TagToProp {
f: undefined;
b: undefined;
i: undefined;
Expand All @@ -23,7 +23,7 @@ type TagToProp = {
fg: Property.Color;
bg: Property.BackgroundColor;
size: Property.FontSize<string | number>;
};
}

type AllTags = keyof TagToProp;
type Tag = {
Expand Down
10 changes: 5 additions & 5 deletions src/Components/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import "purecss/build/pure.css";

import { useCallback, useRef } from "react";

import "purecss/build/pure.css";
// NOTE sweetalert2's ESM export does not setup styles properly, manually importing
import "sweetalert2/dist/sweetalert2.css";

import { injectGlobal, css as stylesheet } from "@emotion/css";
import styled from "@emotion/styled";
import { faCirclePlay, faExternalLink, faInfo, faQuestion } from "@fortawesome/free-solid-svg-icons";
Expand All @@ -11,9 +13,7 @@ import Main from "./Main";
import Swal from "../Classes/SwalReact";
import { codeFontFamily, noop } from "../consts";

// NOTE sweetalert2's ESM export does not setup styles properly, manually importing
import "sweetalert2/dist/sweetalert2.css";

// eslint-disable-next-line @typescript-eslint/no-unused-expressions
injectGlobal`
html,
body {
Expand Down
23 changes: 12 additions & 11 deletions src/Components/CreateSchemaDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChangeEventHandler, forwardRef, RefObject, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { forwardRef, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";

import { css } from "@emotion/react";
Expand All @@ -10,11 +10,12 @@ import ExplorerFolder from "./ExplorerFolder";
import Spinner from "./Spinner";
import actions from "../actions";
import Swal from "../Classes/SwalReact";
import { invalidCharsRegex, newFileTemplate, tshetUinhExamplesURLPrefix, UseMainState } from "../consts";
import { invalidCharsRegex, newFileTemplate, tshetUinhExamplesURLPrefix } from "../consts";
import samples from "../samples";
import { fetchFile, normalizeFileName } from "../utils";

import type { Folder, Sample, SchemaState } from "../consts";
import type { Folder, Sample, SchemaState, UseMainState } from "../consts";
import type { ChangeEventHandler, RefObject } from "react";

const Container = styled.dialog`
transform: scale(0.9);
Expand Down Expand Up @@ -183,12 +184,12 @@ const CreateSchemaDialog = forwardRef<HTMLDialogElement, CreateSchemaDialogProps
{ state: { schemas }, setState, getDefaultFileName, schemaLoaded, hasSchemaName },
ref,
) {
const [createSchemaName, setCreateSchemaName] = useState(() => getDefaultFileName("") + ".js");
const [createSchemaName, setCreateSchemaName] = useState(() => `${getDefaultFileName("")}.js`);
const [createSchemaSample, setCreateSchemaSample] = useState<Sample | "">("");
const [loading, setLoading] = useState(false);

const resetDialog = useCallback(() => {
setCreateSchemaName(getDefaultFileName("") + ".js");
setCreateSchemaName(`${getDefaultFileName("")}.js`);
setCreateSchemaSample("");
setLoading(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand All @@ -199,7 +200,7 @@ const CreateSchemaDialog = forwardRef<HTMLDialogElement, CreateSchemaDialogProps
const name = normalizeFileName(createSchemaName);
if (!name) return "檔案名稱為空";
if (invalidCharsRegex.test(name)) return "檔案名稱含有特殊字元";
if (hasSchemaName(name + ".js")) return "檔案名稱與現有檔案重複";
if (hasSchemaName(`${name}.js`)) return "檔案名稱與現有檔案重複";
return "";
}, [createSchemaName, hasSchemaName]);

Expand All @@ -216,7 +217,7 @@ const CreateSchemaDialog = forwardRef<HTMLDialogElement, CreateSchemaDialogProps
onClick={() => {
const name = normalizeFileName(createSchemaName);
if (!name || name === getDefaultFileName(createSchemaSample))
setCreateSchemaName(getDefaultFileName(sample) + ".js");
setCreateSchemaName(`${getDefaultFileName(sample)}.js`);
setCreateSchemaSample(sample);
}}>
<div>
Expand All @@ -236,9 +237,9 @@ const CreateSchemaDialog = forwardRef<HTMLDialogElement, CreateSchemaDialogProps
setLoading(true);
try {
schemaLoaded({
name: normalizeFileName(createSchemaName) + ".js",
name: `${normalizeFileName(createSchemaName)}.js`,
input: createSchemaSample
? await fetchFile(tshetUinhExamplesURLPrefix + createSchemaSample + ".js")
? await fetchFile(`${tshetUinhExamplesURLPrefix + createSchemaSample}.js`)
: newFileTemplate,
});
} catch {
Expand Down Expand Up @@ -266,7 +267,7 @@ const CreateSchemaDialog = forwardRef<HTMLDialogElement, CreateSchemaDialogProps
setState(
actions.addSchema({
name: "tupa.js",
input: await fetchFile(tshetUinhExamplesURLPrefix + "tupa.js"),
input: await fetchFile(`${tshetUinhExamplesURLPrefix}tupa.js`),
}),
);
Swal.close();
Expand Down Expand Up @@ -296,7 +297,7 @@ const CreateSchemaDialog = forwardRef<HTMLDialogElement, CreateSchemaDialogProps
onClick={() => {
const name = normalizeFileName(createSchemaName);
if (!name || name === getDefaultFileName(createSchemaSample))
setCreateSchemaName(getDefaultFileName("") + ".js");
setCreateSchemaName(`${getDefaultFileName("")}.js`);
setCreateSchemaSample("");
}}>
<div>
Expand Down
3 changes: 2 additions & 1 deletion src/Components/Main.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MutableRefObject, useCallback, useEffect, useReducer, useRef, useState } from "react";
import { useCallback, useEffect, useReducer, useRef, useState } from "react";
import { createPortal } from "react-dom";

import styled from "@emotion/styled";
Expand All @@ -16,6 +16,7 @@ import initialState, { stateStorageLocation } from "../state";
import { copy, notifyError } from "../utils";

import type { MainState, Option, ReactNode } from "../consts";
import type { MutableRefObject } from "react";

const dummyOutput = document.createElement("output");

Expand Down
35 changes: 17 additions & 18 deletions src/Components/SchemaEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { MouseEvent, MutableRefObject } from "react";
import { createPortal } from "react-dom";

import { css } from "@emotion/react";
Expand All @@ -18,6 +17,7 @@ import "../editor/setup";
import { memoize, normalizeFileName, notifyError } from "../utils";

import type { UseMainState, ReactNode } from "../consts";
import type { MouseEvent, MutableRefObject } from "react";

const TabBar = styled.div`
display: flex;
Expand Down Expand Up @@ -234,10 +234,10 @@ export default function SchemaEditor({ state, setState, commonOptions, evaluateH
sample ||= "untitled";
const indices = schemaNames
.map(name => {
if (name === sample + ".js") return 0;
if (!name.startsWith(sample + "-") || !name.endsWith(".js")) return -1;
if (name === `${sample}.js`) return 0;
if (!name.startsWith(`${sample}-`) || !name.endsWith(".js")) return -1;
const start = sample.length + 1;
for (let i = start; i < name.length - 3; i++) if (name[i] < +(i === start) + "" || name[i] > "9") return -1;
for (let i = start; i < name.length - 3; i++) if (name[i] < `${+(i === start)}` || name[i] > "9") return -1;
return +name.slice(start, -3);
})
.sort((a, b) => a - b);
Expand Down Expand Up @@ -268,10 +268,9 @@ export default function SchemaEditor({ state, setState, commonOptions, evaluateH
for (const file of files) {
// POSIX allows all characters other than `\0` and `/` in file names,
// this is necessary to ensure that the file name is valid on all platforms.
const name =
getDefaultFileNameWithSchemaNames(currSchemaNames)(
normalizeFileName(file.name).replace(invalidCharsRegex, "_"),
) + ".js";
const name = `${getDefaultFileNameWithSchemaNames(currSchemaNames)(
normalizeFileName(file.name).replace(invalidCharsRegex, "_"),
)}.js`;
currSchemaNames.push(name);
newState = actions.addSchema({ name, input: contents[i++] })(newState);
}
Expand Down Expand Up @@ -408,7 +407,7 @@ export default function SchemaEditor({ state, setState, commonOptions, evaluateH
const index = schemas.findIndex(schema => schema.name === name);
const children = [].slice.call(tabBarRef.current.children, 0, -1) as HTMLElement[];
const widths = children.map(element => element.getBoundingClientRect().width);
const currentWidth = widths[index] + "px";
const currentWidth = `${widths[index]}px`;
const threshold: number[] = [];
threshold[index] = 0;

Expand All @@ -424,22 +423,22 @@ export default function SchemaEditor({ state, setState, commonOptions, evaluateH
let clientX = startX;

function move(event: { clientX: number } | TouchEvent) {
clientX = "clientX" in event ? event.clientX : (event.touches?.[0]?.clientX ?? clientX);
clientX = "clientX" in event ? event.clientX : (event.touches[0].clientX ?? clientX);
let value = clientX - startX;
children[index].style.left = value + "px";
children[index].style.left = `${value}px`;
if (value < 0) {
value = -value;
for (let i = 0; i < index; i++) children[i].style.left = value >= threshold[i] ? currentWidth : "";
for (let i = length - 1; i > index; i--) children[i].style.left = "";
} else {
for (let i = 0; i < index; i++) children[i].style.left = "";
for (let i = length - 1; i > index; i--)
children[i].style.left = value >= threshold[i] ? "-" + currentWidth : "";
children[i].style.left = value >= threshold[i] ? `-${currentWidth}` : "";
}
}

function end(event: { clientX: number } | TouchEvent) {
clientX = "clientX" in event ? event.clientX : (event.touches?.[0]?.clientX ?? clientX);
clientX = "clientX" in event ? event.clientX : (event.touches[0].clientX ?? clientX);
let value = clientX - startX;
children.forEach(element => (element.style.left = ""));
let i: number;
Expand Down Expand Up @@ -475,7 +474,7 @@ export default function SchemaEditor({ state, setState, commonOptions, evaluateH
const hasSchemaName = (name: string) => schemas.find(schema => schema.name === name);
if (!name) return "檔案名稱為空";
if (invalidCharsRegex.test(name)) return "檔案名稱含有特殊字元";
if (hasSchemaName(name + ".js")) return "檔案名稱與現有檔案重複";
if (hasSchemaName(`${name}.js`)) return "檔案名稱與現有檔案重複";
return "";
}

Expand All @@ -497,15 +496,15 @@ export default function SchemaEditor({ state, setState, commonOptions, evaluateH
confirmButtonText: "確定",
cancelButtonText: "取消",
});
const confirmButton = Swal.getConfirmButton() as HTMLButtonElement;
const confirmButton = Swal.getConfirmButton()!;
confirmButton.disabled = true;
confirmButton.style.pointerEvents = "none";
const input = Swal.getInput() as HTMLInputElement;
const input = Swal.getInput()!;
input.addEventListener("input", () => {
const newName = normalizeFileName(input.value);
const validation = validateFileName(newName);
if (validation) {
if (newName + ".js" !== name) {
if (`${newName}.js` !== name) {
const { selectionStart, selectionEnd, selectionDirection } = input;
Swal.showValidationMessage(validation);
input.setSelectionRange(selectionStart, selectionEnd, selectionDirection || undefined);
Expand All @@ -521,7 +520,7 @@ export default function SchemaEditor({ state, setState, commonOptions, evaluateH
const { isConfirmed, value } = await promise;
if (isConfirmed) {
const newName = normalizeFileName(value);
if (!validateFileName(newName)) setState(actions.renameSchema(name, newName + ".js"));
if (!validateFileName(newName)) setState(actions.renameSchema(name, `${newName}.js`));
}
}
}
Expand Down
11 changes: 6 additions & 5 deletions src/Components/Tooltip.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { cloneElement, ReactElement, useCallback, useEffect, useRef } from "react";
import type { SyntheticEvent } from "react";
import { cloneElement, useCallback, useEffect, useRef } from "react";
import { createRoot } from "react-dom/client";

import { css as stylesheet } from "@emotion/css";

import type { ReactElement, SyntheticEvent } from "react";

function getPageWidth() {
return Math.max(
document.body.scrollWidth,
Expand Down Expand Up @@ -68,9 +69,9 @@ function TooltipAnchor({
targetLeft = Math.min(getPageWidth() - oneRemSize - divInnerBox.width, Math.max(oneRemSize, targetLeft));
targetLeft += window.scrollX;

div.className = tooltipStyle + (fixedWidth ? " " + fixedWidthStyle : "");
div.style.top = targetTop + "px";
div.style.left = targetLeft + "px";
div.className = tooltipStyle + (fixedWidth ? ` ${fixedWidthStyle}` : "");
div.style.top = `${targetTop}px`;
div.style.left = `${targetLeft}px`;
div.style.visibility = "visible";
});

Expand Down
7 changes: 3 additions & 4 deletions src/Components/TooltipChar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,9 @@ export default function TooltipChar({
}
}
各反切. = new Set(Array.from(各反切.).filter(反切 => !各反切..has(反切)));
const 反切text =
(["反", "切"] as const)
.flatMap(x => (各反切[x].size ? [[...各反切[x]].join("/") + x] : []))
.join(" ") + " ";
const 反切text = `${(["反", "切"] as const)
.flatMap(x => (各反切[x].size ? [[...各反切[x]].join("/") + x] : []))
.join(" ")} `;
const 出處text = 來源 && ["廣韻", "王三"].includes(來源.文獻) ? `[${來源.文獻} ${來源.韻目}韻]` : "";
return (
<Fragment key={i}>
Expand Down
2 changes: 1 addition & 1 deletion src/Yitizi.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
declare module "yitizi" {
export const yitiziData: { [c: string]: string };
export const yitiziData: Record<string, string>;
export function get(c: string): string[];
}
2 changes: 1 addition & 1 deletion src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export default {
const schemas = [...state.schemas];
const index = schemas.findIndex(schema => schema.name === name);
const newState = { ...schemas[index], input };
newState.parameters = newState.parameters?.refresh(input) || ParameterSet.from(input);
newState.parameters = newState.parameters.refresh(input) || ParameterSet.from(input);
schemas[index] = newState;
return { ...state, schemas };
},
Expand Down
7 changes: 4 additions & 3 deletions src/consts.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import type { Dispatch, DispatchWithoutAction, ReactChild, ReactPortal, SetStateAction } from "react";

import type { CustomNode } from "./Classes/CustomElement";
import type ParameterSet from "./Classes/ParameterSet";
import type samples from "./samples";
import type { Dispatch, DispatchWithoutAction, ReactChild, ReactPortal, SetStateAction } from "react";
import type { 資料 } from "tshet-uinh";

export const tshetUinhExamplesURLPrefix = "https://cdn.jsdelivr.net/gh/nk2028/tshet-uinh-examples@main/";
Expand Down Expand Up @@ -85,7 +84,9 @@ export type Query = Readonly<Pick<資料.檢索結果, "字頭" | "音韻地位"

type Values<T> = T extends Record<PropertyKey, infer T> ? Values<T> : T;
export type Sample = Values<typeof samples>;
export type Folder = { [name: string]: Folder | Sample };
export interface Folder {
[name: string]: Folder | Sample;
}

type UseGet<K extends string, T> = { [P in K]: T };
type UseSet<K extends string, T> = { [P in `set${Capitalize<K>}`]: Dispatch<SetStateAction<T>> };
Expand Down
9 changes: 5 additions & 4 deletions src/evaluate.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { 推導方案 } from "tshet-uinh-deriver-tools";

import { CustomNode, Formatter } from "./Classes/CustomElement";
import { Formatter } from "./Classes/CustomElement";
import { tshetUinhTextLabelURLPrefix } from "./consts";
import { evaluateOption, getArticle, setArticle } from "./options";
import { fetchFile, normalizeFileName, notifyError } from "./utils";

import type { CustomNode } from "./Classes/CustomElement";
import type { MainState, ReactNode } from "./consts";
import type { 音韻地位 } from "tshet-uinh";
import type { 原始推導函數, 推導函數 } from "tshet-uinh-deriver-tools";
Expand All @@ -26,7 +27,7 @@ export default async function evaluate(state: MainState): Promise<ReactNode> {
const { schemas, option } = state;

if (option === "convertPresetArticle" && !getArticle())
setArticle(await fetchFile(tshetUinhTextLabelURLPrefix + "index.txt"));
setArticle(await fetchFile(`${tshetUinhTextLabelURLPrefix}index.txt`));
else if (option === "compareSchemas" && schemas.length < 2) throw notifyError("此選項需要兩個或以上方案");
else await new Promise(resolve => setTimeout(resolve));

Expand All @@ -47,9 +48,9 @@ export default async function evaluate(state: MainState): Promise<ReactNode> {

function require(current: string, references: string[] = []): Require {
const newReferences = references.concat(current);
if (references.includes(current)) throw notifyError("Circular reference detected: " + newReferences.join(" -> "));
if (references.includes(current)) throw notifyError(`Circular reference detected: ${newReferences.join(" -> ")}`);
return (音韻地位, 字頭) => sample => {
const schema = schemas.find(({ name }) => name === normalizeFileName(sample) + ".js");
const schema = schemas.find(({ name }) => name === `${normalizeFileName(sample)}.js`);
if (!schema) throw notifyError("Schema not found");
return new SchemaFromRequire(rawDeriverFrom(schema.input), require(sample, newReferences), 音韻地位, 字頭);
};
Expand Down
3 changes: 1 addition & 2 deletions src/options.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Fragment } from "react";

import { 資料, 音韻地位 } from "tshet-uinh";
import Yitizi from "yitizi";

Expand Down Expand Up @@ -192,7 +191,7 @@ export const evaluateOption: Record<Option, Handler> = {
return (
<Table
head={[...title(schemas), "計數"]}
body={result.sort((a, b) => b[2] - a[2]).map(([, 擬音陣列, count]) => [...wrap(擬音陣列), count + ""])}
body={result.sort((a, b) => b[2] - a[2]).map(([, 擬音陣列, count]) => [...wrap(擬音陣列), `${count}`])}
/>
);
},
Expand Down
Loading

0 comments on commit 1fd7421

Please sign in to comment.