Skip to content

Commit

Permalink
refactor(messages): update wrapper and make it shareable
Browse files Browse the repository at this point in the history
  • Loading branch information
ph1p committed Jul 28, 2021
1 parent 3dae88f commit 3706dc9
Show file tree
Hide file tree
Showing 18 changed files with 328 additions and 741 deletions.
94 changes: 57 additions & 37 deletions packages/plugin/src/Ui.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Header from '@plugin/components/Header';
import Notifications from '@plugin/components/Notifications';
import { sendMainMessage } from '@plugin/shared/utils';
import {
getStoreFromMain,
StoreProvider,
Expand Down Expand Up @@ -58,18 +57,17 @@ const AppWrapper = styled.div`
overflow: hidden;
`;

// const init = () => {
const App = observer(() => {
const store = useStore();
const [socket, setSocket] = useState<Socket>(null);

const onFocus = () => {
sendMainMessage('focus', false);
EventEmitter.emit('focus', false);
store.setIsFocused(false);
};

const onFocusOut = () => {
sendMainMessage('focus', false);
EventEmitter.emit('focus', false);
store.setIsFocused(false);
};

Expand All @@ -92,41 +90,64 @@ const App = observer(() => {

useEffect(() => {
if (socket && store.status === ConnectionEnum.NONE) {
// sendMainMessage('get-root-data');
EventEmitter.emit('root-data');
socket.on('connect', () => {
store.setStatus(ConnectionEnum.CONNECTED);

socket.emit('set user', store.settings);
socket.emit('join room', {
room: store.roomName,
settings: store.settings,
EventEmitter.ask('root-data').then((rootData: any) => {
const {
roomName: dataRoomName = '',
secret: dataSecret = '',
history: messages = [],
selection = {
page: '',
nodes: [],
},
settings = {},
instanceId = '',
} = rootData;

store.setSecret(dataSecret);
store.setRoomName(dataRoomName);
store.setMessages(messages);
store.setInstanceId(instanceId);
store.setSelection(selection);

store.persistSettings(settings, socket, true);

// socket listener
socket.io.on('error', () => store.setStatus(ConnectionEnum.ERROR));

socket.io.on('reconnect_error', () =>
store.setStatus(ConnectionEnum.ERROR)
);

socket.on('chat message', (data) => {
store.addMessage(data);
});

socket.on('join leave message', (data) => {
const username = data.user.name || 'Anon';
let message = 'joins the conversation';

if (data.type === 'LEAVE') {
message = 'leaves the conversation';
}
store.addNotification(`${username} ${message}`);
});

socket.on('online', (data) => {
store.setOnline(data);
});

store.setStatus(ConnectionEnum.CONNECTED);

socket.emit('set user', store.settings);
socket.emit('join room', {
room: dataRoomName,
settings: store.settings,
});

EventEmitter.emit('ask-for-relaunch-message');
});

sendMainMessage('ask-for-relaunch-message');
});

socket.io.on('error', () => store.setStatus(ConnectionEnum.ERROR));

socket.io.on('reconnect_error', () =>
store.setStatus(ConnectionEnum.ERROR)
);

socket.on('chat message', (data) => {
store.addMessage(data);
});

socket.on('join leave message', (data) => {
const username = data.user.name || 'Anon';
let message = 'joins the conversation';

if (data.type === 'LEAVE') {
message = 'leaves the conversation';
}
store.addNotification(`${username} ${message}`);
});

socket.on('online', (data) => store.setOnline(data));
}

return () => {
Expand Down Expand Up @@ -192,4 +213,3 @@ getStoreFromMain().then((store) => {
);
});
});
// };
52 changes: 12 additions & 40 deletions packages/plugin/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,6 @@ const main = async () => {
let secret = figma.root.getPluginData('secret');
// const ownerId = figma.root.getPluginData('ownerId');

const settings = await figma.clientStorage.getAsync('user-settings');

if (!settings || !settings.url) {
await figma.clientStorage.setAsync('user-settings', {
...settings,
url: DEFAULT_SERVER_URL,
});
}

try {
JSON.parse(history);
} catch {
Expand Down Expand Up @@ -81,16 +72,9 @@ const main = async () => {
secret,
history,
instanceId,
settings,
};
};

const postMessage = (type = '', payload = {}) =>
figma.ui.postMessage({
type,
payload,
});

const getSelectionIds = () => figma.currentPage.selection.map((n) => n.id);

const sendSelection = () => {
Expand All @@ -103,19 +87,6 @@ const sendSelection = () => {
});
};

const sendRootData = async ({ roomName, secret, history, instanceId }) => {
const settings = await figma.clientStorage.getAsync('user-settings');

postMessage('root-data', {
roomName,
secret,
history,
instanceId,
settings,
selection: getSelectionIds(),
});
};

let alreadyAskedForRelaunchMessage = false;

const isValidShape = (node) =>
Expand Down Expand Up @@ -151,15 +122,10 @@ EventEmitter.on('minimize', (flag) => {
figma.ui.resize(flag ? 180 : 333, flag ? 108 : 490);
});

EventEmitter.on('save-user-settings', async (payload, emit) => {
await figma.clientStorage.setAsync('user-settings', payload);
const settings = await figma.clientStorage.getAsync('user-settings');

emit('user-settings', settings);
});

EventEmitter.on('add-message-to-history', (payload) => {
const messageHistory = JSON.parse(figma.root.getPluginData('history'));
const messageHistory = JSON.parse(
figma.root.getPluginData('history') || '[]'
);

figma.root.setPluginData(
'history',
Expand All @@ -169,7 +135,7 @@ EventEmitter.on('add-message-to-history', (payload) => {

EventEmitter.answer(
'get-history',
JSON.parse(figma.root.getPluginData('history'))
JSON.parse(figma.root.getPluginData('history') || '[]')
);

EventEmitter.on('notify', (payload) => {
Expand All @@ -182,10 +148,16 @@ EventEmitter.on('notification', (payload) => {
}
});

EventEmitter.on('root-data', async (_, emit) => {
EventEmitter.answer('root-data', async () => {
const { roomName, secret, history, instanceId } = await main();

emit('root-data', { roomName, secret, history, instanceId });
return {
roomName,
secret,
history,
instanceId,
selection: getSelectionIds(),
};
});

EventEmitter.on('focus', (payload) => {
Expand Down
11 changes: 0 additions & 11 deletions packages/plugin/src/shared/utils.ts

This file was deleted.

22 changes: 18 additions & 4 deletions packages/plugin/src/store/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,26 @@ export class RootStore {
return createEncryptor(this.secret);
}

@ignore
status = ConnectionEnum.NONE;
secret = '';
roomName = '';
instanceId = '';
@ignore
online = [];
@ignore
messages = [];
@ignore
messagesRef = createRef<HTMLDivElement>();

@ignore
secret = '';
@ignore
roomName = '';
@ignore
instanceId = '';

@ignore
autoScrollDisabled = false;

@ignore
selection = undefined;

setStatus(status) {
Expand Down Expand Up @@ -94,8 +105,10 @@ export class RootStore {
}

// ---
@ignore
isFocused = true;

@ignore
isMinimized = false;

settings: StoreSettings = {
Expand All @@ -108,6 +121,7 @@ export class RootStore {
isDarkTheme: false,
};

@ignore
notifications = [];

setSetting(key: keyof StoreSettings, value: string | boolean) {
Expand Down Expand Up @@ -165,7 +179,7 @@ export class RootStore {
};

// save user settings in main
EventEmitter.emit('save-user-settings', { ...toJS(this.settings) });
// EventEmitter.emit('save-user-settings', { ...toJS(this.settings) });

// set server URL
if (!isInit && settings.url && settings.url !== oldUrl) {
Expand Down
Loading

0 comments on commit 3706dc9

Please sign in to comment.