Skip to content

Commit

Permalink
[optimize] simplify models & middlewares with Next-SSR-middleware 0.8…
Browse files Browse the repository at this point in the history
… & MobX-GitHub 0.3

[optimize] TurnDown rules & JSON Edtior updating
  • Loading branch information
TechQuery committed Jun 5, 2024
1 parent 536ab00 commit 9dc6481
Show file tree
Hide file tree
Showing 20 changed files with 144 additions and 434 deletions.
10 changes: 9 additions & 1 deletion components/Form/JSONEditor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,15 @@ export type FieldChangeEvent = ChangeEvent<{ value: FieldProps['value'] }>;
@observer
export class ListField extends Component<FieldProps> {
@observable
accessor innerValue = ListField.metaOf(this.props.value);
accessor innerValue = {} as DataMeta;

componentDidMount() {
this.innerValue = ListField.metaOf(this.props.value);
}

componentDidUpdate({ value }: Readonly<FieldProps>) {
if (value !== this.props.value) this.componentDidMount();
}

static metaOf(value: any): DataMeta {
if (value instanceof Array)
Expand Down
87 changes: 60 additions & 27 deletions components/Form/MarkdownEditor/TurnDown.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,67 @@
import TurnDown from 'turndown';
// @ts-ignore
import { gfm } from 'turndown-plugin-gfm';
import { gfm, strikethrough, tables, taskListItems } from 'turndown-plugin-gfm';

const Empty_HREF = /^(#|javascript:\s*void\(0\);?\s*)$/;

type TurnDownGFM = (td: TurnDown) => void;
export default new TurnDown({
headingStyle: 'atx',
hr: '---',
bulletListMarker: '-',
codeBlockStyle: 'fenced',
linkStyle: 'referenced',
})
.use(strikethrough)
.use(tables)
.use(taskListItems)
.use(gfm)
.addRule('non_url', {
filter: node =>
['a', 'area'].includes(node.nodeName.toLowerCase()) &&
Empty_HREF.test(node.getAttribute('href') || ''),
replacement: (content, node) =>
content.trim() || (node instanceof HTMLElement ? node.title.trim() : ''),
})
.addRule('img-srcset', {
filter: ['img'],
replacement(_, node) {
const { alt, title, src, srcset } = node as HTMLImageElement;
const [firstSet] = srcset.split(',')[0]?.split(/\s+/) || [];

export default class extends TurnDown {
constructor(options?: any) {
super({
headingStyle: 'atx',
hr: '---',
bulletListMarker: '-',
codeBlockStyle: 'fenced',
linkStyle: 'referenced',
...options,
});
const content = [src || firstSet, title && JSON.stringify(title)].filter(
Boolean,
);
return `![${alt}](${content.join(' ')})`;
},
})
.addRule('source-srcset', {
filter: ['picture'],
replacement(_, node) {
const { src, alt, title } = node.querySelector('img') || {};

this.use(gfm as TurnDownGFM)
.addRule('non_url', {
filter: node =>
['a', 'area'].includes(node.nodeName.toLowerCase()) &&
Empty_HREF.test(node.getAttribute('href') || ''),
replacement: (content, node) =>
content.trim() ||
(node instanceof HTMLElement ? node.title.trim() : ''),
})
.addRule('asset_code', {
filter: ['style', 'script'],
replacement: () => '',
});
}
}
const sourceList = Array.from(
node.querySelectorAll('source'),
({ sizes, srcset }) => {
const size = Math.max(
...sizes
.split(/,|\)/)
.map(pixel => parseFloat(pixel.trim()))
.filter(Boolean),
);
const [src] = srcset.split(',')[0]?.split(/\s+/) || [];

return { size, src };
},
);
const sources = sourceList.sort(({ size: a }, { size: b }) => b - a);

const content = [
src || sources[0]?.src,
title && JSON.stringify(title),
].filter(Boolean);

return `![${alt}](${content.join(' ')})`;
},
})
.remove(node => node.matches('style, script, aside, form, [class*="ads" i]'))
.keep('iframe');
8 changes: 4 additions & 4 deletions components/Form/MarkdownEditor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,23 @@ import { observable } from 'mobx';
import { observer } from 'mobx-react';
import {
ClipboardEvent,
Component,
createRef,
DragEvent,
FormEvent,
PureComponent,
} from 'react';
import { insertToCursor, parseDOM } from 'web-utility';

import STYLE from './index.module.less';
import TurnDown from './TurnDown';
import turnDown from './TurnDown';

export type EditorProps = { rules?: any };

type InputHandler = (event: FormEvent) => void;

@observer
export class MarkdownEditor extends PureComponent<EditorProps> {
convertor = new TurnDown();
export class MarkdownEditor extends Component<EditorProps> {
convertor = turnDown;
private contentEditable = createRef<HTMLDivElement>();

get root() {
Expand Down
8 changes: 5 additions & 3 deletions components/Git/ArticleEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { readAs } from 'koajax';
import { debounce } from 'lodash';
import { computed, observable } from 'mobx';
import { GitContent } from 'mobx-github';
import { observer } from 'mobx-react';
import { DataObject } from 'mobx-restful';
import {
Expand All @@ -14,8 +15,7 @@ import { Button, Col, Form } from 'react-bootstrap';
import { blobOf, formatDate, uniqueID } from 'web-utility';
import YAML from 'yaml';

import { GitContent, RepositoryModel } from '../../models/Repository';
import userStore from '../../models/User';
import { GitRepositoryModel, userStore } from '../../models/Repository';
import { ListField } from '../Form/JSONEditor';
import { MarkdownEditor } from '../Form/MarkdownEditor';
import { PathSelect } from './PathSelect';
Expand Down Expand Up @@ -51,7 +51,9 @@ export class ArticleEditor extends Component {
get repositoryStore() {
const { owner } = this.currentRepository;

return new RepositoryModel(owner === userStore.session?.login ? '' : owner);
return new GitRepositoryModel(
owner === userStore.session?.login ? '' : owner,
);
}

path = '';
Expand Down
2 changes: 1 addition & 1 deletion components/Git/Card.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { text2color } from 'idea-react';
import { GitRepository } from 'mobx-github';
import { observer } from 'mobx-react';
import { FC } from 'react';
import { Badge, Button, Card, Col, Row } from 'react-bootstrap';

import { GitRepository } from '../../models/Repository';
import { i18n } from '../../models/Translation';
import { GitLogo } from './Logo';

Expand Down
3 changes: 1 addition & 2 deletions components/Git/Issue/Card.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Icon, Nameplate, text2color } from 'idea-react';
import { marked } from 'marked';
import { Issue } from 'mobx-github';
import { FC } from 'react';
import { Badge, Card, CardProps, Stack } from 'react-bootstrap';

import { Issue } from '../../../models/Repository';

export type IssueCardProps = Issue & Omit<CardProps, 'id' | 'body'>;

export const IssueCard: FC<IssueCardProps> = ({
Expand Down
2 changes: 1 addition & 1 deletion components/Git/Issue/IssueModule.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Icon, text2color } from 'idea-react';
import type { GitRepository } from 'mobx-github';
import { FC, useState } from 'react';
import { Badge, Card, Col, Collapse, Row } from 'react-bootstrap';

import type { GitRepository } from '../../../models/Repository';
import { IssueCard } from './Card';

export const IssueModule: FC<GitRepository> = ({ name, language, issues }) => {
Expand Down
2 changes: 1 addition & 1 deletion components/Git/PathSelect.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Loading } from 'idea-react';
import { observable } from 'mobx';
import { GitContent, RepositoryModel } from 'mobx-github';
import { observer } from 'mobx-react';
import { Component } from 'react';

import { GitContent, RepositoryModel } from '../../models/Repository';
import { SelectInput } from '../Form/SelectInput';

export interface PathSelectProps {
Expand Down
6 changes: 3 additions & 3 deletions components/Git/RepositorySelect.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Loading } from 'idea-react';
import { computed, observable, reaction } from 'mobx';
import { RepositoryModel } from 'mobx-github';
import { observer } from 'mobx-react';
import { Component } from 'react';
import { Col, Row } from 'react-bootstrap';

import { RepositoryModel } from '../../models/Repository';
import userStore from '../../models/User';
import { userStore } from '../../models/Repository';
import { SelectInput } from '../Form/SelectInput';

export type RepositoryIdentity = Record<'owner' | 'name', string>;
Expand Down Expand Up @@ -50,7 +50,7 @@ export class RepositorySelect extends Component<RepositorySelectProps> {
<Col>
<SelectInput
className="form-control"
options={namespaces}
options={namespaces.map(({ login }) => login)}
onBlur={({ currentTarget: { value } }) =>
value.trim() && (this.owner = value)
}
Expand Down
18 changes: 1 addition & 17 deletions models/Base.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import { HTTPClient } from 'koajax';
import { parseCookie } from 'mobx-i18n';

export const isServer = () => typeof window === 'undefined';

const VercelHost = process.env.VERCEL_URL,
GithubToken =
parseCookie(globalThis.document?.cookie || '').token ||
process.env.GITHUB_TOKEN;
const VercelHost = process.env.VERCEL_URL;

export const API_Host = isServer()
? VercelHost
Expand All @@ -18,15 +14,3 @@ export const ownClient = new HTTPClient({
baseURI: `${API_Host}/api/`,
responseType: 'json',
});

export const githubClient = new HTTPClient({
baseURI: isServer() ? 'https://api.github.com/' : `${API_Host}/api/GitHub/`,
responseType: 'json',
}).use(({ request }, next) => {
if (GithubToken)
request.headers = {
authorization: `Bearer ${GithubToken}`,
...request.headers,
};
return next();
});
41 changes: 0 additions & 41 deletions models/Organization.ts

This file was deleted.

Loading

1 comment on commit 9dc6481

@github-actions
Copy link

Choose a reason for hiding this comment

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

Deploy preview for oss-toolbox ready!

✅ Preview
https://oss-toolbox-12f3pfplz-techquerys-projects.vercel.app

Built with commit 9dc6481.
This pull request is being automatically deployed with vercel-action

Please sign in to comment.