12 Commits

Author SHA1 Message Date
Isaac - The456
37e9fa2a0e Add option to wrap text 2025-03-15 11:56:15 +00:00
Luck
0d7cd64eef Update self-hosting instructions 2025-02-23 15:18:45 +00:00
Luck
5b2ca9bd19 Convert to Vite project 2025-01-05 12:02:59 +00:00
mudkip
b31aea56e4 Add Catppuccin theme (#17) 2025-01-05 10:58:31 +00:00
Luck
6bf06ab651 Upgrade dependencies 2024-12-08 22:11:46 +00:00
Matouš Kučera
8936a95ef9 Unified and context diff syntax highlighting (#26) 2024-11-26 23:29:27 +00:00
Duro
60c15956b8 Add lua highlighting (#21) 2024-09-22 08:13:05 +01:00
dvelo
542b0fbde9 Add C and Swift as valid languages (#23) 2024-09-22 08:12:10 +01:00
Luck
fb40855a9a update dependencies 2024-08-24 11:33:15 +01:00
Luck
776a1c5def Add log language highlighting 2023-12-22 21:58:35 +00:00
Luck
5ceca3068e Fix broken css 2023-12-11 22:16:55 +00:00
Luck
b489e1c1c1 Upgrade dependencies 2023-12-03 11:29:57 +00:00
31 changed files with 1446 additions and 9154 deletions

39
.gitignore vendored
View File

@@ -1,25 +1,24 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -5,5 +5,6 @@
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "avoid",
"quoteProps": "consistent"
"quoteProps": "consistent",
"plugins": ["prettier-plugin-organize-imports"]
}

View File

@@ -1,8 +1,8 @@
# Build stage
FROM node:lts as build
FROM node:lts AS build
ARG BYTEBIN_URL="data/"
ENV REACT_APP_BYTEBIN_URL="${BYTEBIN_URL}"
ENV VITE_BYTEBIN_URL="${BYTEBIN_URL}"
WORKDIR /app
COPY package.json yarn.lock ./
@@ -13,6 +13,6 @@ RUN yarn build
# Run stage
FROM nginx:alpine
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/build /usr/share/nginx/html
COPY --from=build /app/dist /usr/share/nginx/html
CMD ["nginx", "-g", "daemon off;"]
EXPOSE 80/tcp

View File

@@ -4,7 +4,7 @@
**paste is a simple web app for writing & sharing code.** It's my own take on conventional pastebin sites like _pastebin.com_ or _hastebin_.
Anyone can use paste! The official/public instance can be accessed using the endpoints listed below, but you can also [host your own](#host-your-own) if you like!
Anyone can use paste! The official/public instance can be accessed using the endpoints listed below, but you can also [host your own](#self-hosting) if you like!
##### 1) In a Web Browser
Just go to https://pastes.dev!
@@ -90,28 +90,13 @@ The API is powered by the [bytebin](https://github.com/lucko/bytebin) service, s
___
### Host your own
### Self-hosting
It's quite simple to host your own version.
The easiest way to self-host is using Docker (& Docker Compose). You can run the following commands to get started:
```bash
git clone https://github.com/lucko/paste
cd paste
yarn install
# Outputs html/css/js files to /build
yarn build
# Start a webserver for testing/development
yarn start
```
You can then follow the [create-react-app deployment documentation](https://create-react-app.dev/docs/deployment/) for how to host the build output. I personally recommend deploying to the cloud using a service like Netlify instead of hosting on your own webserver.
If you really want to self-host (including the bytebin data storage part), I suggest using Docker:
```bash
git clone https://github.com/lucko/paste
docker compose up -d
```

View File

@@ -1,9 +1,10 @@
version: '3.8'
services:
# frontend service
paste:
image: ghcr.io/lucko/paste
# backend service
bytebin:
image: ghcr.io/lucko/bytebin
volumes:
@@ -11,6 +12,7 @@ services:
environment:
BYTEBIN_MISC_KEYLENGTH: 5
# reverse proxy
nginx:
image: nginx:alpine
command: ['nginx', '-g', 'daemon off;']

View File

@@ -1,8 +1,8 @@
# nginx reverse proxy configuration for paste+bytebin
# nginx reverse proxy configuration for paste frontend & bytebin backend
server {
listen 80 default_server;
# paste app
# proxy / path to paste frontend
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
@@ -17,7 +17,7 @@ server {
return 404;
}
# proxy /data endpoint to bytebin
# proxy /data path to bytebin backend
location /data/ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;

28
eslint.config.js Normal file
View File

@@ -0,0 +1,28 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
)

View File

@@ -11,20 +11,21 @@
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="pastes" />
<meta name="twitter:description" content="a simple pastebin." />
<meta name="twitter:image" content="%PUBLIC_URL%/assets/logo256.png" />
<meta name="twitter:image" content="https://pastes.dev/assets/logo256.png" />
<meta property="og:title" content="pastes" />
<meta property="og:description" content="a simple pastebin." />
<meta property="og:type" content="product" />
<meta property="og:image" content="%PUBLIC_URL%/assets/logo256.png" />
<meta property="og:url" content="%PUBLIC_URL%" />
<meta property="og:image" content="https://pastes.dev/assets/logo256.png" />
<meta property="og:url" content="https://pastes.dev" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<link href="%PUBLIC_URL%/assets/logo512.png" rel="shortcut icon" sizes="512x512" type="image/png">
<link rel="apple-touch-icon" href="%PUBLIC_URL%/assets/logo256.png" />
<link rel="icon" href="/favicon.ico" />
<link rel="shortcut icon" href="/assets/logo512.png" sizes="512x512" type="image/png">
<link rel="apple-touch-icon" href="/assets/logo256.png" />
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -2,60 +2,43 @@
"name": "paste",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
"format": "prettier --write '**/*.ts' '**/*.tsx' '**/*.css'"
},
"dependencies": {
"@monaco-editor/react": "^4.5.1",
"copy-to-clipboard": "^3.3.1",
"history": "^5.0.0",
"local-storage": "^2.0.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"@monaco-editor/react": "^4.6.0",
"@catppuccin/palette": "^1.7.1",
"copy-to-clipboard": "^3.3.3",
"history": "^5.3.0",
"monaco-editor": "^0.52.0",
"monaco-themes": "^0.4.4",
"pako": "^2.0.3",
"react": "^18.2.0",
"react-device-detect": "^2.1.2",
"react-dom": "^18.2.0",
"react-scripts": "^5.0.1",
"styled-components": "^5.2.1",
"typescript": "^4.8.4",
"pako": "^2.1.0",
"react-device-detect": "^2.2.3",
"styled-components": "^6.1.13",
"whatwg-mimetype": "^3.0.0"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^14.2.0",
"@types/jest": "^29.2.2",
"@types/node": "^18.11.9",
"@types/pako": "^2.0.0",
"@types/react": "^18.0.25",
"@types/react-dom": "^18.0.8",
"@types/styled-components": "^5.1.26",
"@types/whatwg-mimetype": "^3.0.0",
"monaco-editor": "^0.34.1",
"prettier": "^2.7.1",
"prettier-plugin-organize-imports": "^3.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"format": "prettier --write '**/*.ts' '**/*.tsx' '**/*.css'",
"compile": "tsc"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
"@eslint/js": "^9.17.0",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"@types/pako": "^2.0.3",
"@types/whatwg-mimetype": "^3.0.2",
"@vitejs/plugin-react-swc": "^3.5.0",
"eslint": "^9.17.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.16",
"globals": "^15.14.0",
"typescript": "~5.6.2",
"typescript-eslint": "^8.18.2",
"vite": "^6.0.5",
"prettier": "^3.4.2",
"prettier-plugin-organize-imports": "^4.1.0"
}
}

View File

@@ -9,7 +9,7 @@ const Button = styled.div`
color: inherit;
text-decoration: none;
:hover {
&:hover {
background: ${props => props.theme.highlight};
}

View File

@@ -27,7 +27,7 @@ export default function Editor({
}: EditorProps) {
const [language, setLanguage] = useState<string>('plain');
const [readOnly, setReadOnly] = useState<boolean>(isMobile && !!pasteId);
const resetFunction = useRef<ResetFunction>();
const resetFunction = useRef<ResetFunction>(null);
const [theme, setTheme] = usePreference<keyof Themes>(
'theme',
@@ -40,6 +40,8 @@ export default function Editor({
pref => pref >= 10 && pref <= 22
);
const [wordWrap, setWordWrap] = usePreference<boolean>('wordwrap-enabled', true, (value) => true)
useEffect(() => {
if (contentType) {
setLanguage(contentType);
@@ -66,6 +68,8 @@ export default function Editor({
setReadOnly={setReadOnly}
theme={theme}
setTheme={setTheme}
wordWrap={wordWrap}
setWordWrap={setWordWrap}
zoom={zoom}
/>
<EditorTextArea
@@ -76,6 +80,7 @@ export default function Editor({
language={language}
fontSize={fontSize}
readOnly={readOnly}
wordWrap={wordWrap}
resetFunction={resetFunction}
/>
</ThemeProvider>

View File

@@ -1,6 +1,6 @@
import copy from 'copy-to-clipboard';
import history from 'history/browser';
import { MutableRefObject, useCallback, useEffect, useState } from 'react';
import { RefObject, useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import themes, { Themes } from '../style/themes';
@@ -12,13 +12,15 @@ import MenuButton from './MenuButton';
export interface EditorControlsProps {
actualContent: string;
resetFunction: MutableRefObject<ResetFunction | undefined>;
resetFunction: RefObject<ResetFunction | null>;
language: string;
setLanguage: (value: string) => void;
readOnly: boolean;
setReadOnly: (value: boolean) => void;
theme: keyof Themes;
setTheme: (value: keyof Themes) => void;
wordWrap: boolean
setWordWrap: (value: boolean) => void;
zoom: (delta: number) => void;
}
@@ -31,6 +33,8 @@ export default function EditorControls({
setReadOnly,
theme,
setTheme,
wordWrap,
setWordWrap,
zoom,
}: EditorControlsProps) {
const [saving, setSaving] = useState<boolean>(false);
@@ -113,6 +117,7 @@ export default function EditorControls({
<Section>
<Button onClick={() => zoom(1)}>[+ </Button>
<Button onClick={() => zoom(-1)}> -]</Button>
<Button onClick={() => setWordWrap(!wordWrap)}>[<span className='optional'>wrap:</span>{wordWrap ? "on" : "off"}]</Button>
<MenuButton
label="theme"
value={theme}
@@ -136,7 +141,7 @@ export default function EditorControls({
const Header = styled.header`
position: fixed;
top: 0;
z-index: 2;
z-index: 10;
width: 100%;
height: 2em;
color: ${props => props.theme.primary};

View File

@@ -1,7 +1,6 @@
import { createGlobalStyle, ThemeProps } from 'styled-components';
import { Theme } from '../style/themes';
import { createGlobalStyle } from 'styled-components';
const EditorGlobalStyle = createGlobalStyle<ThemeProps<Theme>>`
const EditorGlobalStyle = createGlobalStyle`
html, body {
color-scheme: ${props => props.theme.lightOrDark};
scrollbar-color: ${props => props.theme.lightOrDark};

View File

@@ -5,8 +5,9 @@ import Editor, {
OnMount,
} from '@monaco-editor/react';
import history from 'history/browser';
import React, {
import {
MutableRefObject,
RefObject,
useCallback,
useEffect,
useRef,
@@ -16,8 +17,43 @@ import styled from 'styled-components';
import themes, { Theme } from '../style/themes';
import type { editor } from 'monaco-editor';
import { diffLanguage } from '../util/languages/diff';
import { logLanguage } from '../util/languages/log';
import { ResetFunction } from './Editor';
import { loader } from '@monaco-editor/react';
import * as monaco from 'monaco-editor';
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker';
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker';
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';
self.MonacoEnvironment = {
getWorker(_: string, label: string): Promise<Worker> | Worker {
switch (label) {
case 'json':
return new jsonWorker();
case 'css':
case 'scss':
case 'less':
return new cssWorker();
case 'html':
case 'handlebars':
case 'razor':
return new htmlWorker();
case 'typescript':
case 'javascript':
return new tsWorker();
default:
return new editorWorker();
}
},
};
loader.config({ monaco });
export interface EditorTextAreaProps {
forcedContent: string;
actualContent: string;
@@ -26,7 +62,8 @@ export interface EditorTextAreaProps {
language: string;
fontSize: number;
readOnly: boolean;
resetFunction: MutableRefObject<ResetFunction | undefined>;
wordWrap: boolean;
resetFunction: MutableRefObject<ResetFunction | null>;
}
export default function EditorTextArea({
@@ -37,6 +74,7 @@ export default function EditorTextArea({
language,
fontSize,
readOnly,
wordWrap,
resetFunction,
}: EditorTextAreaProps) {
const [editor, setEditor] = useState<editor.IStandaloneCodeEditor>();
@@ -60,6 +98,11 @@ export default function EditorTextArea({
monaco.editor.defineTheme(theme.id, theme.editor);
}
monaco.languages.register({ id: 'log' });
monaco.languages.setMonarchTokensProvider('log', logLanguage);
monaco.languages.register({ id: 'diff' });
monaco.languages.setMonarchTokensProvider('diff', diffLanguage);
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
noSemanticValidation: true,
noSyntaxValidation: true,
@@ -125,7 +168,7 @@ export default function EditorTextArea({
fontFamily: 'JetBrains Mono',
fontSize: fontSize,
fontLigatures: true,
wordWrap: 'on',
wordWrap: wordWrap ? 'on' : 'off',
renderLineHighlight: 'none',
renderValidationDecorations: 'off',
readOnly,
@@ -242,7 +285,7 @@ function useSelectedLine(): [SelectedLine, ToggleSelectedFunction] {
}
function useLineNumberMagic(
editorAreaRef: React.RefObject<HTMLDivElement>,
editorAreaRef: RefObject<HTMLDivElement | null>,
selected: SelectedLine,
toggleSelected: ToggleSelectedFunction,
forcedContent: string,
@@ -257,13 +300,13 @@ function useLineNumberMagic(
}
const handler = (click: MouseEvent) => {
const target = click?.target as HTMLElement;
const element = document.elementFromPoint(click.x, click.y);
if (
target &&
target.classList.contains('line-numbers') &&
target.textContent
element &&
element.classList.contains('line-numbers') &&
element.textContent
) {
toggleSelected(parseInt(target.textContent), click);
toggleSelected(parseInt(element.textContent), click);
}
};

View File

@@ -19,7 +19,7 @@ export default function MenuButton<T extends string>({
// close the menu when a click is made elsewhere
useEffect(() => {
const listener = (e: MouseEvent) => setOpen(false);
const listener = () => setOpen(false);
window.addEventListener('click', listener);
return () => window.removeEventListener('click', listener);
}, [setOpen]);
@@ -92,7 +92,7 @@ const Menu = styled.ul`
}
> li.selected {
::before {
&::before {
content: '*';
font-weight: bold;
}

View File

@@ -1,4 +1,3 @@
import { get as lsGet, remove as lsRemove, set as lsSet } from 'local-storage';
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
// hook used to load "preference" settings from local storage, or fall back to a default value.
@@ -8,8 +7,9 @@ export default function usePreference<T>(
valid: (value: T) => boolean
): [T, Dispatch<SetStateAction<T>>, (value: T) => boolean] {
const [value, setValue] = useState<T>(() => {
const pref = lsGet(id) as T;
if (pref && valid(pref)) {
const prefRaw = localStorage.getItem(id);
const pref = prefRaw !== null ? (JSON.parse(prefRaw) as T) : undefined;
if (pref !== null && pref !== undefined && valid(pref)) {
return pref;
} else {
return defaultValue;
@@ -18,9 +18,9 @@ export default function usePreference<T>(
useEffect(() => {
if (value === defaultValue) {
lsRemove(id);
localStorage.removeItem(id);
} else {
lsSet(id, value);
localStorage.setItem(id, JSON.stringify(value));
}
}, [value, id, defaultValue]);

View File

@@ -2,6 +2,7 @@ import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './style/base.css';
import type {} from './style/styled';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement

7
src/style/styled.d.ts vendored Normal file
View File

@@ -0,0 +1,7 @@
import 'styled-components';
import { Theme } from './themes';
declare module 'styled-components' {
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface DefaultTheme extends Theme {}
}

View File

@@ -1,11 +1,13 @@
import type { editor } from 'monaco-editor';
import { CatppuccinFlavor, ColorFormat, flavors } from '@catppuccin/palette';
import dracula from 'monaco-themes/themes/Dracula.json';
import monokai from 'monaco-themes/themes/Monokai.json';
import solarizedDark from 'monaco-themes/themes/Solarized-dark.json';
import solarizedLight from 'monaco-themes/themes/Solarized-light.json';
type Color = `#${string}`;
type ColorRecord = Record<string, Color>;
export interface Theme {
id: string;
@@ -28,6 +30,10 @@ export interface Themes {
'monokai': Theme;
'solarized': Theme;
'solarized-light': Theme;
'latte': Theme;
'frappe': Theme;
'macchiato': Theme;
'mocha': Theme;
}
const themes: Themes = {
@@ -44,7 +50,8 @@ const themes: Themes = {
backgroundColor: '#161b22', // canvas.overlay
},
editor: makeMonacoTheme({
editor: makeMonacoTheme(
{
base: 'vs-dark',
colors: {
primary: '#c9d1d9', // fg.default
@@ -59,8 +66,18 @@ const themes: Themes = {
keyword: '#ff7b72',
type: '#ffa657',
variable: '#ffa657',
logInfo: '#3fb950', // green.3
logError: '#f85149', // red.4
logWarning: '#d29922', // yellow.3
logDate: '#33B3AE', // teal.3
logException: '#f8e3a1', // yellow.0
diffMeta: '#33B3AE', // teal.3
diffAddition: '#3fb950', // green.3
diffDeletion: '#f85149', // red.4
},
}),
},
{}
),
},
'light': {
id: 'light',
@@ -75,7 +92,8 @@ const themes: Themes = {
backgroundColor: '#e0f6ff',
},
editor: makeMonacoTheme({
editor: makeMonacoTheme(
{
base: 'vs',
colors: {
primary: '#000000',
@@ -90,8 +108,18 @@ const themes: Themes = {
keyword: '#0077aa',
type: '#DD4A68',
variable: '#ee9900',
logInfo: '#2da44e', // green.4
logError: '#cf222e', // red.5
logWarning: '#d4a72c', // yellow.3
logDate: '#136061', // teal.6
logException: '#7d4e00', // yellow.6
diffMeta: '#136061', // teal.6
diffAddition: '#2da44e', // green.4
diffDeletion: '#cf222e', // red.5
},
}),
},
{}
),
},
'dracula': {
id: 'dracula',
@@ -104,7 +132,16 @@ const themes: Themes = {
color: '#586e75',
backgroundColor: '#44475a',
},
editor: dracula as editor.IStandaloneThemeData,
editor: addExtraColors(dracula as editor.IStandaloneThemeData, {
logInfo: '#50FA7B', // green
logError: '#FF5555', // red
logWarning: '#FFB86C', // orange
logDate: '#BD93F9', // purple
logException: '#F1FA8C', // yellow
diffMeta: '#BD93F9', // purple
diffAddition: '#50FA7B', // green
diffDeletion: '#FF5555', // red
}),
},
'monokai': {
id: 'monokai',
@@ -117,7 +154,16 @@ const themes: Themes = {
color: '#49483E',
backgroundColor: '#3E3D32',
},
editor: monokai as editor.IStandaloneThemeData,
editor: addExtraColors(monokai as editor.IStandaloneThemeData, {
logInfo: '#a6e22e', // green
logError: '#f92672', // red
logWarning: '#fd971f', // orange
logDate: '#AB9DF2', // purple
logException: '#F1FA8C', // yellow
diffMeta: '#AB9DF2', // purple
diffAddition: '#a6e22e', // green
diffDeletion: '#f92672', // red
}),
},
'solarized': {
id: 'solarized',
@@ -130,7 +176,16 @@ const themes: Themes = {
color: '#93a1a1', // base1
backgroundColor: '#073642', // base02
},
editor: solarizedDark as editor.IStandaloneThemeData,
editor: addExtraColors(solarizedDark as editor.IStandaloneThemeData, {
logInfo: '#268bd2', // blue
logError: '#dc322f', // red
logWarning: '#b58900', // yellow
logDate: '#2aa198', // cyan
logException: '#859900', // green
diffMeta: '#2aa198', // cyan
diffAddition: '#859900', // green
diffDeletion: '#dc322f', // red
}),
},
'solarized-light': {
id: 'solarized-light',
@@ -143,12 +198,36 @@ const themes: Themes = {
color: '#586e75', // base01
backgroundColor: '#eee8d5', // base2
},
editor: solarizedLight as editor.IStandaloneThemeData,
editor: addExtraColors(solarizedLight as editor.IStandaloneThemeData, {
logInfo: '#268bd2', // blue
logError: '#dc322f', // red
logWarning: '#b58900', // yellow
logDate: '#2aa198', // cyan
logException: '#859900', // green
diffMeta: '#2aa198', // cyan
diffAddition: '#859900', // green
diffDeletion: '#dc322f', // red
}),
},
'latte': createCatppuccinTheme(flavors.latte),
'frappe': createCatppuccinTheme(flavors.frappe),
'macchiato': createCatppuccinTheme(flavors.macchiato),
'mocha': createCatppuccinTheme(flavors.mocha),
};
export default themes;
interface ExtraColors {
logInfo: Color;
logError: Color;
logWarning: Color;
logDate: Color;
logException: Color;
diffMeta: Color;
diffAddition: Color;
diffDeletion: Color;
}
interface MonacoThemeProps {
base: 'vs' | 'vs-dark';
colors: {
@@ -164,11 +243,12 @@ interface MonacoThemeProps {
keyword: Color;
type: Color;
variable: Color;
};
} & ExtraColors;
}
export function makeMonacoTheme(
props: MonacoThemeProps
props: MonacoThemeProps,
extraColors: ColorRecord
): editor.IStandaloneThemeData {
const colors = Object.fromEntries(
Object.entries(props.colors).map(([key, color]) => [
@@ -177,6 +257,11 @@ export function makeMonacoTheme(
])
) as Record<keyof MonacoThemeProps['colors'], string>;
const editorColors: ColorRecord = {
'editor.background': `#${colors.background}`,
'editor.foreground': `#${colors.primary}`,
};
return {
base: props.base,
inherit: true,
@@ -202,10 +287,99 @@ export function makeMonacoTheme(
{ token: 'identifier', foreground: colors.primary },
{ token: 'type', foreground: colors.type },
{ token: 'comment', foreground: colors.comment },
{ token: 'info.log', foreground: colors.logInfo },
{ token: 'error.log', foreground: colors.logError, fontStyle: 'bold' },
{ token: 'warning.log', foreground: colors.logWarning },
{ token: 'date.log', foreground: colors.logDate },
{ token: 'exception.log', foreground: colors.logException },
{ token: 'meta.diff', foreground: colors.diffMeta },
{ token: 'addition.diff', foreground: colors.diffAddition },
{ token: 'deletion.diff', foreground: colors.diffDeletion },
],
colors: {
'editor.background': `#${colors.background}`,
'editor.foreground': `#${colors.primary}`,
},
colors: { ...editorColors, ...extraColors },
};
}
export function addExtraColors(
theme: editor.IStandaloneThemeData,
extraColors: ExtraColors
): editor.IStandaloneThemeData {
const colors = Object.fromEntries(
Object.entries(extraColors).map(([key, color]) => [key, color.substring(1)])
) as Record<keyof ExtraColors, string>;
theme.rules.push(
...[
{ token: 'info.log', foreground: colors.logInfo },
{ token: 'error.log', foreground: colors.logError, fontStyle: 'bold' },
{ token: 'warning.log', foreground: colors.logWarning },
{ token: 'date.log', foreground: colors.logDate },
{ token: 'exception.log', foreground: colors.logException },
{ token: 'meta.diff', foreground: colors.diffMeta },
{ token: 'addition.diff', foreground: colors.diffAddition },
{ token: 'deletion.diff', foreground: colors.diffDeletion },
]
);
return theme;
}
export function createCatppuccinTheme(flavor: CatppuccinFlavor): Theme {
const color = (color: ColorFormat) => color.hex as Color;
const nameToId: Record<string, string> = {
[flavors.latte.name]: 'latte',
[flavors.frappe.name]: 'frappe',
[flavors.macchiato.name]: 'macchiato',
[flavors.mocha.name]: 'mocha',
};
const editorTheme = makeMonacoTheme(
{
base: flavor.dark ? 'vs-dark' : 'vs',
colors: {
// Monaco
primary: color(flavor.colors.text),
background: color(flavor.colors.mantle),
string: color(flavor.colors.green),
comment: color(flavor.colors.overlay2),
delimiter: color(flavor.colors.overlay2),
annotation: color(flavor.colors.yellow),
constant: color(flavor.colors.peach),
number: color(flavor.colors.peach),
operator: color(flavor.colors.sky),
keyword: color(flavor.colors.mauve),
type: color(flavor.colors.yellow),
variable: color(flavor.colors.text),
// Log Files
logDate: color(flavor.colors.mauve),
logInfo: color(flavor.colors.green),
logWarning: color(flavor.colors.yellow),
logError: color(flavor.colors.red),
logException: color(flavor.colors.yellow),
// Diff Files
diffMeta: color(flavor.colors.sky),
diffAddition: color(flavor.colors.green),
diffDeletion: color(flavor.colors.red),
},
},
{
'editorBracketHighlight.foreground1': color(flavor.colors.overlay2),
'editorBracketHighlight.foreground2': color(flavor.colors.overlay2),
'editorBracketHighlight.foreground3': color(flavor.colors.overlay2),
}
);
return {
id: nameToId[flavor.name],
lightOrDark: flavor.dark ? 'dark' : 'light',
primary: color(flavor.colors.text),
secondary: color(flavor.colors.base),
highlight: color(flavor.colors.surface0),
background: color(flavor.colors.mantle),
highlightedLine: {
color: color(flavor.colors.rosewater),
backgroundColor: color(flavor.colors.surface2),
},
editor: editorTheme,
};
}

View File

@@ -1,4 +1,3 @@
export const bytebinUrl =
process.env.REACT_APP_BYTEBIN_URL || 'https://bytebin.lucko.me/';
import.meta.env.VITE_BYTEBIN_URL || 'https://bytebin.lucko.me/';
export const postUrl = bytebinUrl + 'post';

View File

@@ -1,4 +1,5 @@
export const languages = {
text: ['plain', 'log'],
config: ['yaml', 'json', 'xml', 'ini'],
code: [
'java',
@@ -6,6 +7,7 @@ export const languages = {
'typescript',
'python',
'kotlin',
'scala',
'cpp',
'csharp',
'shell',
@@ -13,12 +15,12 @@ export const languages = {
'rust',
'sql',
'go',
'lua',
'swift',
'c',
],
web: ['html', 'css', 'php'],
misc: ['plain', 'dockerfile', 'markdown'],
web: ['html', 'css', 'scss', 'php', 'graphql'],
misc: ['diff', 'dockerfile', 'markdown', 'proto'],
};
// missing following the rewrite: toml, properties, log, javastacktrace, groovy, haskell, protobuf
// would be good to add these back with custom language definitions
export const languageIds = Object.values(languages).flat(1);

View File

@@ -0,0 +1,30 @@
import { languages } from 'monaco-editor';
export const diffLanguage: languages.IMonarchLanguage = {
defaultToken: '',
tokenizer: {
root: [
// Meta lines (e.g., @@ -1,2 +3,4 @@)
[/@@@ +-\d+,\d+ +\+\d+,\d+ +@@@/, 'meta'],
[/^\*\*\* +\d+,\d+ +\*\*\*\*$/, 'meta'],
[/^--- +\d+,\d+ +----$/, 'meta'],
// Comments
[/Index: .*/, 'comment'],
[/^index.*/, 'comment'],
[/={3,}/, 'comment'],
[/^-{3}.*/, 'comment'],
[/^\*{3} .*/, 'comment'],
[/^\+{3}.*/, 'comment'],
[/^diff --git.*/, 'comment'],
[/^\*{15}$/, 'comment'],
// Additions
[/^\+.*/, 'addition'],
[/^!.*/, 'addition'],
// Deletions
[/^-.*/, 'deletion'],
],
},
};

71
src/util/languages/log.ts Normal file
View File

@@ -0,0 +1,71 @@
import type { languages } from 'monaco-editor';
// Source:
// - https://github.com/emilast/vscode-logfile-highlighter/blob/master/syntaxes/log.tmLanguage
// - https://github.com/sumy7/monaco-language-log/blob/main/language-log.js
export const logLanguage: languages.IMonarchLanguage = {
defaultToken: '',
tokenizer: {
// prettier-ignore
root: [
// Trace/Verbose
[/\b(Trace)\b:/, 'verbose'],
// Serilog VERBOSE
[/\[(verbose|verb|vrb|vb|v)]/i, 'verbose'],
// Android logcat Verbose
[/\bV\//, 'verbose'],
// DEBUG
[/\b(DEBUG|Debug)\b|\b([dD][eE][bB][uU][gG]):/, 'debug'],
// Serilog DEBUG
[/\[(debug|dbug|dbg|de|d)]/i, 'debug'],
// Android logcat Debug
[/\bD\//, 'debug'],
// INFO
[/\b(HINT|INFO|INFORMATION|Info|NOTICE|II)\b|\b([iI][nN][fF][oO]|[iI][nN][fF][oO][rR][mM][aA][tT][iI][oO][nN]):/, 'info'],
// serilog INFO
[/\[(information|info|inf|in|i)]/i, 'info'],
// Android logcat Info
[/\bI\//, 'info'],
// WARN
[/\b(WARNING|WARN|Warn|WW)\b|\b([wW][aA][rR][nN][iI][nN][gG]):/, 'warning'],
// Serilog WARN
[/\[(warning|warn|wrn|wn|w)]/i, 'warning'],
// Android logcat Warning
[/\bW\//, 'warning'],
// ERROR
[/\b(ALERT|CRITICAL|EMERGENCY|ERROR|FAILURE|FAIL|Fatal|FATAL|Error|EE)\b|\b([eE][rR][rR][oO][rR]):/, 'error'],
// Serilog ERROR
[/\[(error|eror|err|er|e|fatal|fatl|ftl|fa|f)]/i, 'error'],
// Android logcat Error
[/\bE\//, 'error'],
// ISO dates ("2020-01-01")
[/\b\d{4}-\d{2}-\d{2}(T|\b)/, 'date'],
// Culture specific dates ("01/01/2020", "01.01.2020")
[/\b\d{2}[^\w\s]\d{2}[^\w\s]\d{4}\b/, 'date'],
// Clock times with optional timezone ("01:01:01", "01:01:01.001", "01:01:01+01:01")
[/\d{1,2}:\d{2}(:\d{2}([.,]\d{1,})?)?(Z| ?[+-]\d{1,2}:\d{2})?\b/, 'date'],
// Git commit hashes of length 40, 10, or 7
//[/\b([0-9a-fA-F]{40}|[0-9a-fA-F]{10}|[0-9a-fA-F]{7})\b/, 'constant'],
// Guids
[/[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}/, 'constant'],
// MAC addresses: 89:A1:23:45:AB:C0, fde8:e767:269c:0:9425:3477:7c8f:7f1a
//[/\b([0-9a-fA-F]{2,}[:-])+([0-9a-fA-F]{2,})+\b/, 'constant'],
// Constants
//[/\b([0-9]+|true|false|null)\b/, 'constant'],
// Hex Constants
[/\b(0x[a-fA-F0-9]+)\b/, 'constant'],
// String constants
[/"[^"]*"/, 'string'],
[/(?<![\w])'[^']*'/, 'string'],
// Colorize rows of exception call stacks
[/[\t ]*at[\t ]+.*$/, 'exception'],
[/Exception in thread ".*" .*$/, 'exception'],
// Exception type names
[/\b([a-zA-Z.]*Exception)\b/, 'exception'],
// Match Urls
[/\b(http|https|ftp|file):\/\/\S+\b\/?/, 'constant'],
// Match character and . sequences (such as namespaces) as well as file names and extensions (e.g. bar.txt)
//[/(?<![\w/\\])([\w-]+\.)+([\w-])+(?![\w/\\])/, 'constant'],
],
},
};

View File

@@ -31,7 +31,7 @@ export async function loadFromBytebin(id: string): Promise<LoadResult> {
} else {
return { ok: false };
}
} catch (e) {
} catch {
return { ok: false };
}
}

9
src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_BYTEBIN_URL?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}

26
tsconfig.app.json Normal file
View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

View File

@@ -1,27 +1,7 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src/*.ts",
"src/*.tsx"
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

24
tsconfig.node.json Normal file
View File

@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

7
vite.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import react from '@vitejs/plugin-react-swc';
import { defineConfig } from 'vite';
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
});

9773
yarn.lock

File diff suppressed because it is too large Load Diff