Skip to content

Commit

Permalink
🦄 refactor: Optimize code readability
Browse files Browse the repository at this point in the history
  • Loading branch information
xiangechen committed Apr 25, 2024
1 parent 654d048 commit fdd71d8
Show file tree
Hide file tree
Showing 78 changed files with 592 additions and 1,026 deletions.
7 changes: 2 additions & 5 deletions packages/chili-core/src/command/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export abstract class CancelableCommand extends Observable implements ICanclable
}

get document() {
return this._application!.activeView?.document!;
return this.application.activeView?.document!;
}

private _controller?: AsyncController;
Expand All @@ -51,10 +51,7 @@ export abstract class CancelableCommand extends Observable implements ICanclable
@Property.define("common.cancel")
async cancel() {
this.controller?.cancel();
while (true) {
if (this._isCompleted) {
break;
}
while (!this._isCompleted) {
await new Promise((r) => setTimeout(r, 30));
}
}
Expand Down
6 changes: 3 additions & 3 deletions packages/chili-core/src/command/decarator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ export namespace Command {
if (typeof command === "string") {
let c = CommandMap.get(command);
return c?.prototype.data;
} else if (typeof command === "function") {
}
if (typeof command === "function") {
return command.prototype.data;
} else {
return Object.getPrototypeOf(command).data;
}
return Object.getPrototypeOf(command).data;
}

export function get(name: CommandKeys): CommandConstructor | undefined {
Expand Down
18 changes: 10 additions & 8 deletions packages/chili-core/src/foundation/binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export class Binding<T extends IPropertyChanged = any> {
element: new WeakRef(element),
property,
};

this.setValue<U>(element, property);
this.source.onPropertyChanged(this._onPropertyChanged);
registry.register(element, this);
Expand All @@ -51,19 +52,20 @@ export class Binding<T extends IPropertyChanged = any> {
};

private setValue<U extends object>(element: U, property: PropertyKey) {
let value: any = this.getPropertyValue();
let value = this.getPropertyValue();
(element as any)[property] = value;
}

getPropertyValue() {
let value: any = this.source[this.path];
if (this.converter) {
let result = this.converter.convert(value);
if (!result.isOk) {
throw new Error(`Cannot convert value ${value}`);
}
value = result.value;
if (!this.converter) {
return value;
}

let result = this.converter.convert(value);
if (!result.isOk) {
throw new Error(`Cannot convert value ${value}`);
}
return value;
return result.value;
}
}
47 changes: 26 additions & 21 deletions packages/chili-core/src/foundation/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,21 @@ export class ObservableCollection<T> implements ICollectionChanged, IDisposable
}

move(from: number, to: number) {
if (from === to) return;
if (from >= 0 && from < this._items.length && to >= 0 && to < this._items.length) {
let items = this._items.splice(from, 1);
this._items.splice(from < to ? to - 1 : to, 0, ...items);
this._callbacks.forEach((callback) =>
callback({
action: CollectionAction.move,
from,
to,
}),
);
let canMove =
from !== to && from >= 0 && from < this._items.length && to >= 0 && to < this._items.length;
if (!canMove) {
return;
}

let items = this._items.splice(from, 1);
this._items.splice(from < to ? to - 1 : to, 0, ...items);
this._callbacks.forEach((callback) =>
callback({
action: CollectionAction.move,
from,
to,
}),
);
}

clear() {
Expand All @@ -93,17 +96,19 @@ export class ObservableCollection<T> implements ICollectionChanged, IDisposable
}

replace(index: number, ...items: T[]) {
if (index >= 0 && index < this._items.length) {
let item = this._items[index];
this._items.splice(index, 1, ...items);
this._callbacks.forEach((callback) =>
callback({
action: CollectionAction.replace,
item,
items,
}),
);
if (index < 0 || index >= this._items.length) {
return;
}

let item = this._items[index];
this._items.splice(index, 1, ...items);
this._callbacks.forEach((callback) =>
callback({
action: CollectionAction.replace,
item,
items,
}),
);
}

forEach(callback: (item: T, index: number) => void) {
Expand Down
2 changes: 1 addition & 1 deletion packages/chili-core/src/foundation/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export class History implements IDisposable {

private tryOperate(action: () => void) {
let isDisabled = this.disabled;
if (!isDisabled) this.disabled = true;
if (!this.disabled) this.disabled = true;
try {
action();
} finally {
Expand Down
26 changes: 13 additions & 13 deletions packages/chili-core/src/foundation/linkedList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,20 @@ export class LinkedList<T> {

insert(index: number, item: T) {
let node = this.nodeAt(index);
if (node) {
const newNode: LinkedListNode<T> = {
data: item,
next: node,
prev: node.prev,
};
if (node.prev) {
node.prev.next = newNode;
} else {
this._head = newNode;
}
node.prev = newNode;
this._size++;
if (!node) return;

const newNode: LinkedListNode<T> = {
data: item,
next: node,
prev: node.prev,
};
if (node.prev) {
node.prev.next = newNode;
} else {
this._head = newNode;
}
node.prev = newNode;
this._size++;
}

remove(item: T) {
Expand Down
52 changes: 21 additions & 31 deletions packages/chili-core/src/foundation/utils/readFileAsync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,17 @@ export interface FileData {
export async function readFileAsync(
accept: string,
multiple: boolean,
reader: "readAsText" | "readAsDataURL" = "readAsText",
method: "readAsText" | "readAsDataURL" = "readAsText",
): Promise<Result<FileData[]>> {
return new Promise((resolve, _reject) => {
let result: FileData[] = [];
let input = document.createElement("input");
input.type = "file";
input.multiple = multiple;
input.style.visibility = "hidden";
input.accept = accept;
input.style.visibility = "hidden";
input.onchange = async () => {
document.body.removeChild(input);
await resolveFiles(input, result, resolve, reader);
resolve(await readInputedFiles(input, method));
};
input.oncancel = () => {
document.body.removeChild(input);
Expand All @@ -32,40 +31,31 @@ export async function readFileAsync(
});
}

async function resolveFiles(
input: HTMLInputElement,
result: FileData[],
resolve: (value: Result<FileData[]> | PromiseLike<Result<FileData[]>>) => void,
reader: "readAsText" | "readAsDataURL",
) {
if (!input.files) {
resolve(Result.err(`no files`));
return;
}
for (let i = 0; i < input.files.length; i++) {
let file = input.files.item(i);
if (!file) continue;
let data = await asyncFileReader(file, reader);
if (data.isOk) {
result.push({
fileName: file.name,
data: data.value,
});
} else {
resolve(Result.err(data.error));
async function readInputedFiles(input: HTMLInputElement, method: "readAsText" | "readAsDataURL") {
let files = input.files ?? [];
let result: FileData[] = [];
for (const file of files) {
let data = await readFileDataAsync(file, method);
if (!data) {
return Result.err(`Error occurred reading file: ${file.name}`);
}

result.push({
fileName: file.name,
data,
});
}
resolve(Result.ok(result));
return Result.ok(result);
}

function asyncFileReader(file: File, method: any): Promise<Result<string>> {
return new Promise((resolve, reject) => {
function readFileDataAsync(file: File, method: any): Promise<string | undefined> {
return new Promise((resolve) => {
let reader = new FileReader();
reader.onload = (e) => {
resolve(Result.ok(e.target!.result as string));
resolve(e.target!.result as string);
};
reader.onerror = (e) => {
resolve(Result.err(`Error occurred reading file: ${file.name}`));
reader.onerror = () => {
resolve(undefined);
};
(reader as any)[method](file);
});
Expand Down
36 changes: 22 additions & 14 deletions packages/chili-core/src/i18n/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,35 @@ export type Locale = {

export type Translation = Record<I18nKeys, string>;

export namespace I18n {
let languageIndex = navigator.language.toLowerCase() === "zh-cn" ? 0 : 1;
export enum Language {
English,
Chinese,
}

export const languages = [zh, en];
export namespace I18n {
export const languages = new Map<Language, Locale>([
[Language.English, en],
[Language.Chinese, zh],
]);

export function currentIndex() {
return languageIndex;
let _currentLanguage =
navigator.language.toLowerCase() === "zh-cn" ? Language.Chinese : Language.English;
export function currentLanguage() {
return _currentLanguage;
}

export function combineTranslation(code: "zh-CN" | "en", translations: Record<string, string>) {
let language = languages.find((lang) => lang.code === code);
if (language) {
language.translation = {
...language.translation,
export function combineTranslation(language: Language, translations: Record<string, string>) {
let local = languages.get(language);
if (local) {
local.translation = {
...local.translation,
...translations,
};
}
}

export function translate(key: I18nKeys, ...args: any[]) {
let text = languages[languageIndex].translation[key];
let text = languages.get(_currentLanguage)!.translation[key];
if (args.length > 0) {
text = text.replace(/\{(\d+)\}/g, (_, index) => args[index]);
}
Expand All @@ -54,9 +62,9 @@ export namespace I18n {
}
}

export function changeLanguage(idx: number): boolean {
if (idx < 0 || idx >= languages.length || languageIndex === idx) return false;
languageIndex = idx;
export function changeLanguage(language: Language): boolean {
if (!languages.has(language)) return false;
_currentLanguage = language;
document.querySelectorAll(`[data-${I18nId}]`).forEach((e) => {
let html = e as HTMLElement;
let id = html?.dataset[I18nId] as I18nKeys;
Expand Down
26 changes: 16 additions & 10 deletions packages/chili-core/src/math/planeAngle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,29 @@ export class PlaneAngle {
let dotX = vec.dot(this.plane.xvec);
let dotY = vec.dot(this.plane.yvec);

if (
((this._preDotY < -Precision.Distance &&
dotY > Precision.Distance &&
this._angle < Precision.Distance) ||
(this._preDotY > -Precision.Distance &&
dotY < -Precision.Distance &&
this._angle > -Precision.Distance)) && // 确保穿过 0
this._preDotX > 0 &&
dotX > 0
) {
if (this.crossXAxisAtXGreatThan0(dotX, dotY)) {
this._reverse = !this._reverse;
}

this._angle = (this.plane.xvec.angleOnPlaneTo(vec, this.plane.normal)! * 180) / Math.PI;
if (this._reverse) {
this._angle -= 360;
}

if (Math.abs(dotX) > Precision.Distance) this._preDotX = dotX;
if (Math.abs(dotY) > Precision.Distance) this._preDotY = dotY;
}

private crossXAxisAtXGreatThan0(dotX: number, dotY: number) {
let crossXfromBottomToTop =
this._preDotY < -Precision.Distance &&
dotY > Precision.Distance &&
this._angle < Precision.Angle;
let crossXfromTopToBottom =
this._preDotY > -Precision.Distance &&
dotY < -Precision.Distance &&
this._angle > -Precision.Angle;
let crossX = crossXfromBottomToTop || crossXfromTopToBottom;
return crossX && this._preDotX > 0 && dotX > 0;
}
}
Loading

0 comments on commit fdd71d8

Please sign in to comment.