Visualize Your Ideas With Code
feature: code component
aarthificial6879af55f77f
diff --git a/package-lock.json b/package-lock.jsonindex 18549133..a5429732 100644--- a/package-lock.json+++ b/package-lock.json@@ -9,13 +9,16 @@"version": "1.2.0","license": "ISC","dependencies": {+ "@types/dom-webcodecs": "^0.1.4","@types/wicg-file-system-access": "^2020.9.5","canvas": "^2.9.1","image-size": "^1.0.1","konva": "^8.3.2","meow": "^10.1.2","mix-color": "^1.1.2",+ "mp4box": "^0.5.2","preact": "^10.7.1",+ "prismjs": "^1.28.0","strongly-typed-events": "^3.0.1","three": "^0.138.3","ts-loader": "^9.2.6",@@ -31,6 +34,7 @@},"devDependencies": {"@types/node-sass": "^4.11.2",+ "@types/prismjs": "^1.26.0","@types/three": "^0.138.0","@types/webpack-env": "^1.17.0","css-loader": "^6.7.1",@@ -262,6 +266,11 @@"@types/node": "*"}},+ "node_modules/@types/dom-webcodecs": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.4.tgz",+ "integrity": "sha512-dc+xSUnCaCdi/hExZArnLhiavS3E1Rdpp2+zCI6TcmJvz4qgDPBbpvCM7DsQhwRXIIpVMHO6c3s+t+JyCSqYBA=="+ },"node_modules/@types/eslint": {"version": "8.4.1","resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.4.1.tgz",@@ -348,6 +357,12 @@"resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.1.tgz","integrity": "sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw=="},+ "node_modules/@types/prismjs": {+ "version": "1.26.0",+ "resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.0.tgz",+ "integrity": "sha512-ZTaqn/qSqUuAq1YwvOFQfVW1AR/oQJlLSZVustdjwI+GZ8kr0MSHBj0tsXPW1EqHubx50gtBEjbPGsdZwQwCjQ==",+ "dev": true+ },"node_modules/@types/qs": {"version": "6.9.7","resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.7.tgz",@@ -3417,6 +3432,11 @@"node": ">=10"}},+ "node_modules/mp4box": {+ "version": "0.5.2",+ "resolved": "https://registry.npmjs.org/mp4box/-/mp4box-0.5.2.tgz",+ "integrity": "sha512-zRmGlvxy+YdW3Dmt+TR4xPHynbxwXtAQDTN/Fo9N3LMxaUlB2C5KmZpzYyGKy4c7k4Jf3RCR0A2pm9SZELOLXw=="+ },"node_modules/ms": {"version": "2.1.2","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",@@ -4284,6 +4304,14 @@"node": ">=10.13.0"}},+ "node_modules/prismjs": {+ "version": "1.28.0",+ "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.28.0.tgz",+ "integrity": "sha512-8aaXdYvl1F7iC7Xm1spqSaY/OJBpYW3v+KJ+F17iYxvdc8sfjW194COK5wVhMZX45tGteiBQgdvD/nhxcRwylw==",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/process-nextick-args": {"version": "2.0.1","resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",@@ -6543,6 +6571,11 @@"@types/node": "*"}},+ "@types/dom-webcodecs": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.4.tgz",+ "integrity": "sha512-dc+xSUnCaCdi/hExZArnLhiavS3E1Rdpp2+zCI6TcmJvz4qgDPBbpvCM7DsQhwRXIIpVMHO6c3s+t+JyCSqYBA=="+ },"@types/eslint": {"version": "8.4.1","resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.4.1.tgz",@@ -6629,6 +6662,12 @@"resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.1.tgz","integrity": "sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw=="},+ "@types/prismjs": {+ "version": "1.26.0",+ "resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.0.tgz",+ "integrity": "sha512-ZTaqn/qSqUuAq1YwvOFQfVW1AR/oQJlLSZVustdjwI+GZ8kr0MSHBj0tsXPW1EqHubx50gtBEjbPGsdZwQwCjQ==",+ "dev": true+ },"@types/qs": {"version": "6.9.7","resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.7.tgz",@@ -8979,6 +9018,11 @@"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz","integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw=="},+ "mp4box": {+ "version": "0.5.2",+ "resolved": "https://registry.npmjs.org/mp4box/-/mp4box-0.5.2.tgz",+ "integrity": "sha512-zRmGlvxy+YdW3Dmt+TR4xPHynbxwXtAQDTN/Fo9N3LMxaUlB2C5KmZpzYyGKy4c7k4Jf3RCR0A2pm9SZELOLXw=="+ },"ms": {"version": "2.1.2","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",@@ -9593,6 +9637,11 @@"integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==","dev": true},+ "prismjs": {+ "version": "1.28.0",+ "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.28.0.tgz",+ "integrity": "sha512-8aaXdYvl1F7iC7Xm1spqSaY/OJBpYW3v+KJ+F17iYxvdc8sfjW194COK5wVhMZX45tGteiBQgdvD/nhxcRwylw=="+ },"process-nextick-args": {"version": "2.0.1","resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",diff --git a/package.json b/package.jsonindex 9ee500e4..4750f197 100644--- a/package.json+++ b/package.json@@ -11,13 +11,16 @@},"types": "dist/global.d.ts","dependencies": {+ "@types/dom-webcodecs": "^0.1.4","@types/wicg-file-system-access": "^2020.9.5","canvas": "^2.9.1","image-size": "^1.0.1","konva": "^8.3.2","meow": "^10.1.2","mix-color": "^1.1.2",+ "mp4box": "^0.5.2","preact": "^10.7.1",+ "prismjs": "^1.28.0","strongly-typed-events": "^3.0.1","three": "^0.138.3","ts-loader": "^9.2.6",@@ -38,6 +41,7 @@],"devDependencies": {"@types/node-sass": "^4.11.2",+ "@types/prismjs": "^1.26.0","@types/three": "^0.138.0","@types/webpack-env": "^1.17.0","css-loader": "^6.7.1",diff --git a/src/components/LayoutText.ts b/src/components/LayoutText.tsindex e7eecbf1..181768b9 100644--- a/src/components/LayoutText.ts+++ b/src/components/LayoutText.ts@@ -21,7 +21,6 @@ export class LayoutText extends Text {padd: new Spacing(30),align: 'center',verticalAlign: 'middle',- height: 20,fontSize: 28,fontFamily: 'JetBrains Mono',fill: 'rgba(30, 30, 30, 0.87)',@@ -32,13 +31,28 @@ export class LayoutText extends Text {public getLayoutSize(custom?: LayoutTextConfig): Size {const padding = this.getPadd();- const size = this.measureSize(custom?.text ?? this.text());+ let size: Size;+ if (custom?.text) {+ const text = this.text();+ this.text(custom.text);+ size = {+ width: this.textWidth,+ height: this.textHeight,+ }+ this.text(text);+ } else {+ size = {+ width: this.textWidth,+ height: this.textHeight,+ }+ }+return {width: Math.max(custom?.minWidth ?? this.getMinWidth(),this.overrideWidth ?? size.width + padding.x,),- height: (this.isConstructed ? this.getHeight() : 0) + padding.y,+ height: this.height() + padding.y,};}diff --git a/src/components/ThreeView.ts b/src/components/ThreeView.tsindex 7d22059c..bcb1d0ce 100644--- a/src/components/ThreeView.ts+++ b/src/components/ThreeView.ts@@ -136,9 +136,7 @@ export class ThreeView extends Shape {this.renderedFrames--;}- context._context.save();context._context.imageSmoothingEnabled = false;-context._context.clip(CanvasHelper.roundRectPath(new Path2D(),@@ -160,6 +158,5 @@ export class ThreeView extends Shape {size.width,size.height,);- context._context.restore();}}diff --git a/src/components/code/Code.tsx b/src/components/code/Code.tsxnew file mode 100644index 00000000..a7aaca67--- /dev/null+++ b/src/components/code/Code.tsx@@ -0,0 +1,316 @@+import {getset, KonvaNode, threadable} from '../../decorators';+import {GetSet} from 'konva/lib/types';+import PrismJS from 'prismjs';+import {Context} from 'konva/lib/Context';+import {Text, TextConfig} from 'konva/lib/shapes/Text';+import {Util} from 'konva/lib/Util';+import {easeOutExpo, tween} from '../../tweening';+import {CodeTheme} from './CodeTheme';+import {JS_CODE_THEME} from '../../themes';++type CodePoint = [number, number];+type CodeRange = [CodePoint, CodePoint];++interface CodeConfig extends TextConfig {+ selection?: CodeRange[];+ theme?: CodeTheme;+}++@KonvaNode({centroid: false})+export class Code extends Text {+ @getset([])+ public selection: GetSet<CodeConfig['selection'], this>;+ @getset(JS_CODE_THEME)+ public theme: GetSet<CodeConfig['theme'], this>;++ private readonly textCanvas: HTMLCanvasElement;+ private readonly textCtx: CanvasRenderingContext2D;+ private readonly selectionCanvas: HTMLCanvasElement;+ private readonly selectionCtx: CanvasRenderingContext2D;++ private outline: number = 0;+ private unselectedOpacity = 1;++ public constructor(config?: CodeConfig) {+ super({+ fontFamily: 'JetBrains Mono',+ fontSize: 28,+ lineHeight: 2,+ ...config,+ });+ this.textCanvas = Util.createCanvasElement();+ this.textCtx = this.textCanvas.getContext('2d');+ this.selectionCanvas = Util.createCanvasElement();+ this.selectionCtx = this.selectionCanvas.getContext('2d');+ }++ public _sceneFunc(context: Context) {+ const padding = this.getPadd();++ context.translate(padding.left, padding.right);+ this.drawSelection(context._context);+ this.drawText(context._context);+ }++ private drawSelection(context: CanvasRenderingContext2D) {+ const lines = this.text().split('\n');+ const letterWidth = this.measureSize(' ').width;+ const lineHeight = this.fontSize() * this.lineHeight();+ const selection = [...this.selection()];+ const outline = this.outline;++ context.beginPath();+ for (const range of selection) {+ let [[startLine, startColumn], [endLine, endColumn]] = range;++ if (startLine >= lines.length) {+ startLine = lines.length - 1;+ }++ if (endLine >= lines.length) {+ endLine = lines.length - 1;+ }++ if (endColumn >= lines[endLine].length) {+ endColumn = Math.max(lines[endLine].length, 1);+ }++ if (startLine !== endLine) {+ const nextLineOffset =+ startLine + 1 === endLine+ ? endColumn+ : Math.max(1, lines[startLine + 1].length);++ if (nextLineOffset <= startColumn) {+ selection.push([+ [startLine + 1, 0],+ [endLine, endColumn],+ ]);+ endLine = startLine;+ endColumn = lines[startLine].length;+ }+ }++ let offset =+ startLine === endLine+ ? endColumn * letterWidth+ : Math.max(1, lines[startLine].length) * letterWidth;+ context.moveTo(+ startColumn * letterWidth - outline,+ (startLine + 0.5) * lineHeight,+ );+ context.arcTo(+ startColumn * letterWidth - outline,+ startLine * lineHeight - outline,+ offset + outline,+ startLine * lineHeight - outline,+ 8,+ );++ context.arcTo(+ offset + outline,+ startLine * lineHeight - outline,+ offset + outline,+ (startLine + 1) * lineHeight,+ 8,+ );++ for (let i = startLine + 1; i <= endLine; i++) {+ const lineOffset =+ Math.max(1, i === endLine ? endColumn : lines[i].length) *+ letterWidth;+ const linePadding = lineOffset > offset ? -outline : outline;+ context.arcTo(+ offset + outline,+ i * lineHeight + linePadding,+ lineOffset + outline,+ i * lineHeight + linePadding,+ 8,+ );+ offset = lineOffset;+ context.arcTo(+ offset + outline,+ i * lineHeight + linePadding,+ offset + outline,+ (i + 1) * lineHeight + linePadding,+ 8,+ );+ }++ const endOffset = startLine === endLine ? startColumn * letterWidth : 0;+ context.arcTo(+ offset + outline,+ (endLine + 1) * lineHeight + outline,+ endOffset - outline,+ (endLine + 1) * lineHeight + outline,+ 8,+ );+ context.arcTo(+ endOffset - outline,+ (endLine + 1) * lineHeight + outline,+ endOffset - outline,+ endLine * lineHeight + outline,+ 8,+ );+ if (startLine !== endLine) {+ context.arcTo(+ endOffset - outline,+ (startLine + 1) * lineHeight - outline,+ startColumn * letterWidth - outline,+ (startLine + 1) * lineHeight - outline,+ 8,+ );+ context.arcTo(+ startColumn * letterWidth - outline,+ (startLine + 1) * lineHeight - outline,+ startColumn * letterWidth - outline,+ startLine * lineHeight - outline,+ 8,+ );+ }+ context.lineTo(+ startColumn * letterWidth - outline,+ (startLine + 0.5) * lineHeight,+ );+ }++ context.closePath();+ context.fillStyle = '#242424';+ context.fill();+ }++ private drawText(context: CanvasRenderingContext2D) {+ const letterWidth = this.measureSize(' ').width;+ const lineHeight = this.fontSize() * this.lineHeight();+ const tokens = PrismJS.tokenize(this.text(), PrismJS.languages.javascript);+ const theme = this.theme();++ context.font = this._getContextFont();+ context.textBaseline = 'middle';++ let x = 0;+ let y = 0;+ for (const token of tokens) {+ if (typeof token === 'string') {+ context.fillStyle = theme.punctuation ?? theme.fallback;+ if (token.includes('\n')) {+ const words = token.split('\n');+ for (let i = 0; i < words.length; i++) {+ if (i > 0) {+ x = 0;+ y++;+ }++ context.globalAlpha = this.getOpacity(x, y);+ context.fillText(words[i], x * letterWidth, (y + 0.5) * lineHeight);+ x += words[i].length;+ }+ } else {+ context.globalAlpha = this.getOpacity(x, y);+ context.fillText(+ token as string,+ x * letterWidth,+ (y + 0.5) * lineHeight,+ );+ x += token.length;+ }+ } else {+ context.fillStyle = theme[token.type] ?? theme.fallback;+ context.globalAlpha = this.getOpacity(x, y);+ context.fillText(+ token.content as string,+ x * letterWidth,+ (y + 0.5) * lineHeight,+ );+ x += token.length;+ }+ }+ }++ private getOpacity(x: number, y: number): number {+ return this.isSelected(x, y) ? 1 : this.unselectedOpacity;+ }++ private isSelected(x: number, y: number): boolean {+ if (this.selection().length === 0) {+ return false;+ }++ return !!this.selection().find(+ ([[startLine, startColumn], [endLine, endColumn]]) => {+ return (+ ((y === startLine && x >= startColumn) || y > startLine) &&+ ((y === endLine && x < endColumn) || y < endLine)+ );+ },+ );+ }++ public selectLines(from: number, to?: number): this {+ this.selection([+ [+ [from, 0],+ [to ?? from, Infinity],+ ],+ ]);+ return this;+ }++ public selectWord(line: number, from: number, to?: number): this {+ this.selection([+ [+ [line, from],+ [line, to ?? Infinity],+ ],+ ]);+ return this;+ }++ public selectRange(+ startLine: number,+ startColumn: number,+ endLine: number,+ endColumn: number,+ ): this {+ this.selection([+ [+ [startLine, startColumn],+ [endLine, endColumn],+ ],+ ]);+ return this;+ }++ public clearSelection(): this {+ this.selection([]);+ return this;+ }++ public hasSelection(): boolean {+ return this.selection().length > 0;+ }++ public apply() {+ this.outline = 0;+ this.unselectedOpacity = this.hasSelection() ? 0.32 : 1;+ }++ @threadable('animateCode')+ public *animate() {+ const hasSelection = this.hasSelection();+ const currentOpacity = this.unselectedOpacity;++ yield* tween(+ 0.5,+ value => {+ this.outline = easeOutExpo(value, -8, 0);+ this.unselectedOpacity = easeOutExpo(+ value,+ currentOpacity,+ hasSelection ? 0.32 : 1,+ );+ },+ () => this.apply(),+ );+ }+}diff --git a/src/components/code/CodeTheme.ts b/src/components/code/CodeTheme.tsnew file mode 100644index 00000000..b83c02fe--- /dev/null+++ b/src/components/code/CodeTheme.ts@@ -0,0 +1,22 @@+export type CodeTheme = Record<string, string> & {fallback: string};++export interface JSCodeTheme {+ boolean?: string;+ 'class-name'?: string;+ comment?: string;+ constant?: string;+ function?: string;+ 'function-variable'?: string;+ hashbang?: string;+ keyword?: string;+ 'literal-property'?: string;+ number?: string;+ operator?: string;+ parameter?: string;+ punctuation?: string;+ regex?: string;+ string?: string;+ 'string-property'?: string;+ 'template-string'?: string;+ fallback: string;+}diff --git a/src/components/code/index.ts b/src/components/code/index.tsnew file mode 100644index 00000000..415856c5--- /dev/null+++ b/src/components/code/index.ts@@ -0,0 +1,2 @@+export * from './CodeTheme';+export * from './Code';\ No newline at end of filediff --git a/src/themes/code.ts b/src/themes/code.tsnew file mode 100644index 00000000..fca1bb2d--- /dev/null+++ b/src/themes/code.ts@@ -0,0 +1,30 @@+import {JSCodeTheme} from '../components/code';++const KEYWORD = '#ff6470';+const TEXT = '#ACB3BF';+const FUNCTION = '#ffc66d';+const STRING = '#99C47A';+const NUMBER = '#68ABDF';+const PROPERTY = '#AC7BB5';+const COMMENT = '#a9b7c6';++export const JS_CODE_THEME: JSCodeTheme = {+ boolean: KEYWORD,+ constant: KEYWORD,+ keyword: KEYWORD,+ 'class-name': TEXT,+ operator: TEXT,+ punctuation: TEXT,+ function: FUNCTION,+ string: STRING,+ number: NUMBER,+ 'literal-property': PROPERTY,+ comment: COMMENT,+ 'function-variable': '#ff00ff',+ hashbang: '#ff00ff',+ parameter: '#ff00ff',+ regex: '#ff00ff',+ 'string-property': '#ff00ff',+ 'template-string': '#ff00ff',+ fallback: '#ff00ff',+};diff --git a/src/themes/index.ts b/src/themes/index.tsnew file mode 100644index 00000000..b0a9eeb9--- /dev/null+++ b/src/themes/index.ts@@ -0,0 +1 @@+export * from './code';\ No newline at end of file