Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: support compile decorator #5595

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@
"@nx/vite": "17.2.8",
"@perfsee/sdk": "^1.9.0",
"@playwright/test": "^1.40.0",
"@rollup/plugin-swc": "^0.3.0",
"@swc/core": "^1.3.102",
"@taplo/cli": "^0.5.2",
"@testing-library/react": "^14.1.2",
"@toeverything/infra": "workspace:*",
Expand All @@ -73,7 +75,6 @@
"@typescript-eslint/parser": "^6.13.1",
"@vanilla-extract/vite-plugin": "^3.9.2",
"@vanilla-extract/webpack-plugin": "^2.3.1",
"@vitejs/plugin-react-swc": "^3.5.0",
"@vitest/coverage-istanbul": "1.1.3",
"@vitest/ui": "1.1.3",
"electron": "^27.1.0",
Expand Down
3 changes: 3 additions & 0 deletions packages/common/infra/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"./command": "./src/command/index.ts",
"./atom": "./src/atom/index.ts",
"./app-config-storage": "./src/app-config-storage.ts",
"./livedata": "./src/livedata/index.ts",
".": "./src/index.ts"
},
"dependencies": {
Expand All @@ -16,9 +17,11 @@
"@blocksuite/blocks": "0.12.0-nightly-202401180838-f0c45fd",
"@blocksuite/global": "0.12.0-nightly-202401180838-f0c45fd",
"@blocksuite/store": "0.12.0-nightly-202401180838-f0c45fd",
"foxact": "^0.2.20",
"jotai": "^2.5.1",
"jotai-effect": "^0.2.3",
"nanoid": "^5.0.3",
"react": "18.2.0",
"tinykeys": "^2.1.0",
"yjs": "^13.6.10",
"zod": "^3.22.4"
Expand Down
6 changes: 3 additions & 3 deletions packages/common/infra/src/blocksuite/migration/subdoc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,9 @@ function runBlockMigration(
}

function migrateSurface(data: YMap<unknown>) {
for (const [, value] of <IterableIterator<[string, YMap<unknown>]>>(
data.entries()
)) {
for (const [, value] of data.entries() as IterableIterator<
[string, YMap<unknown>]
>) {
if (value.get('type') === 'connector') {
migrateSurfaceConnector(value);
}
Expand Down
62 changes: 62 additions & 0 deletions packages/common/infra/src/livedata/__tests__/livedata.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { map, Observable, of } from 'rxjs';
import { describe, expect, test, vitest } from 'vitest';
import * as Y from 'yjs';

import { LiveData } from '..';

describe('livedata', () => {
test('LiveData', async () => {
const livedata = new LiveData(0);
expect(livedata.value).toBe(0);
livedata.next(1);
expect(livedata.value).toBe(1);
let subscribed = 0;
livedata.subscribe(v => {
subscribed = v;
});
livedata.next(2);
expect(livedata.value).toBe(2);
await vitest.waitFor(() => subscribed === 2);
});

test('from', async () => {
{
const livedata = LiveData.from(of(1, 2, 3, 4), 0);
expect(livedata.value).toBe(4);
}
{
const livedata1 = new LiveData(1);
const livedata2 = LiveData.from(livedata1.pipe(map(v => 'live' + v)), '');
expect(livedata2.value).toBe('live1');
livedata1.next(2);
expect(livedata2.value).toBe('live2');
}

{
let observableClosed = false;
const observable = new Observable(() => {
return () => {
observableClosed = true;
};
});
const livedata = LiveData.from(observable, 0);
livedata.complete();
expect(
observableClosed,
'should close parent observable, when livedata complete'
).toBe(true);
}
});

test('from yjs', async () => {
const ydoc = new Y.Doc();
const ymap = ydoc.getMap('test');

const livedata = LiveData.fromY<any>(ymap);
expect(livedata.value).toEqual({});
ymap.set('a', 1);
expect(livedata.value).toEqual({ a: 1 });
ymap.set('b', 2);
expect(livedata.value).toEqual({ a: 1, b: 2 });
});
});
115 changes: 115 additions & 0 deletions packages/common/infra/src/livedata/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { DebugLogger } from '@affine/debug';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs';

const logger = new DebugLogger('livedata');

/**
* LiveData is a reactive data type.
*
* ## basic usage
*
* @example
* ```ts
* const livedata = new LiveData(0); // create livedata with initial value
*
* livedata.next(1); // update value
*
* console.log(livedata.value); // get current value
*
* livedata.subscribe(v => { // subscribe to value changes
* console.log(v); // 1
* });
* ```
*
* ## observable
*
* LiveData is a rxjs observable, you can use rxjs operators.
*
* @example
* ```ts
* new LiveData(0).pipe(
* map(v => v + 1),
* filter(v => v > 1),
* ...
* )
* ```
*
* NOTICE: different from normal observable, LiveData will always emit the latest value when you subscribe to it.
*
* ## from observable
*
* LiveData can be created from observable or from other livedata.
*
* @example
* ```ts
* const A = LiveData.from(
* of(1, 2, 3, 4), // from observable
* 0 // initial value
* );
*
* const B = LiveData.from(
* A.pipe(map(v => 'from a ' + v)), // from other livedata
* '' // initial value
* );
* ```
*
* NOTICE: LiveData.from will not complete when the observable completes, you can use `spreadComplete` option to change
* this behavior.
*
* @see {@link https://rxjs.dev/api/index/class/BehaviorSubject}
*/
export class LiveData<T = unknown> extends BehaviorSubject<T> {
static from<T>(
observable: Observable<T>,
initialValue: T,
{ spreadComplete = false }: { spreadComplete?: boolean } = {}
): LiveData<T> {
const data = new LiveData(initialValue);

const subscription = observable.subscribe({
next(value) {
data.next(value);
},
error(err) {
if (spreadComplete) {
data.error(err);
} else {
logger.error('uncatched error in livedata', err);
}
},
complete() {
if (spreadComplete) {
data.complete();
}
},
});
data.subscribe({
complete() {
subscription.unsubscribe();
},
error() {
subscription.unsubscribe();
},
});

return data;
}

static fromY<T>(ydata: any): LiveData<T> {
if (typeof ydata.toJSON !== 'function') {
throw new Error('unsupported yjs type');
}

return LiveData.from<T>(
new Observable(subscriber => {
ydata.observeDeep(() => {
subscriber.next(ydata.toJSON());
});
}),
ydata.toJSON()
);
}
}

export * from './react';
41 changes: 41 additions & 0 deletions packages/common/infra/src/livedata/react.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { use } from 'foxact/use';
import { useEffect, useState } from 'react';

import type { LiveData } from '.';

/**
* subscribe LiveData and return the value.
*/
export function useLiveData<T>(liveData: LiveData<T>): T {
const [data, setData] = useState(liveData.value);

useEffect(() => {
const subscription = liveData.subscribe(value => {
setData(value);
});
return () => subscription.unsubscribe();
}, [liveData]);

return data;
}

/**
* subscribe LiveData and return the value. If the value is nullish, will suspends until the value is not nullish.
*/
export function useEnsureLiveData<T>(liveData: LiveData<T>): NonNullable<T> {
const data = useLiveData(liveData);

if (data === null || data === undefined) {
return use(
new Promise(resolve => {
liveData.subscribe(value => {
if (value === null || value === undefined) {
resolve(value);
}
});
})
);
}

return data;
}
3 changes: 3 additions & 0 deletions packages/frontend/core/.webpack/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ export const createConfiguration: (

resolve: {
symlinks: true,
// some package use '.js' to import '.ts' files for compatibility with moduleResolution: node
extensionAlias: {
'.js': ['.js', '.tsx', '.ts'],
'.mjs': ['.mjs', '.mts'],
Expand Down Expand Up @@ -267,6 +268,8 @@ export const createConfiguration: (
},
},
useDefineForClassFields: false,
legacyDecorator: true,
decoratorMetadata: true,
},
experimental: {
plugins: [
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@
"@perfsee/webpack": "^1.8.4",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.11",
"@sentry/webpack-plugin": "^2.8.0",
"@swc/core": "^1.3.93",
"@swc/core": "^1.3.102",
"@testing-library/react": "^14.0.0",
"@types/animejs": "^3",
"@types/bytes": "^3.1.3",
Expand Down
44 changes: 44 additions & 0 deletions scripts/rollup-plugin-swc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { createFilter } from '@rollup/pluginutils';
import { transform } from '@swc/core';
import type { Plugin } from 'vite';

const queryRE = /\?.*$/;
const hashRE = /#.*$/;
const cleanUrl = (url: string) => url.replace(hashRE, '').replace(queryRE, '');

export function RollupPluginSwc(): Plugin {
const filter = createFilter(/\.(tsx?|jsx)$/, /\.js$/);

return {
name: 'rollup-plugin-swc',
async transform(code, id) {
if (filter(id) || filter(cleanUrl(id))) {
const result = await transform(code, {
jsc: {
target: 'esnext',
parser: {
syntax: 'typescript',
tsx: true,
decorators: true,
},
transform: {
react: {
runtime: 'automatic',
importSource: '@emotion/react',
},
legacyDecorator: true,
decoratorMetadata: true,
},
},
filename: id,
sourceMaps: true,
});
return {
code: result.code,
map: result.map,
};
}
return;
},
};
}
Loading