Skip to content

optimize state handlers #32

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
27 changes: 14 additions & 13 deletions src/scripts/appjs/memoryFileStorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,30 +9,31 @@
import FileManager from './fileManager';

export default class MemoryFileStorage {
constructor() {
this.storage = {};
}
storage = {};

// eslint-disable-next-line class-methods-use-this
isAvailable() {
return true;
}

getFile(fileName) {
async getFile(fileName) {
if (this.storage[fileName]) {
return Promise.resolve(this.storage[fileName]);
return this.storage[fileName];
}
return Promise.reject(new Error('FILE_NOT_FOUND'));
throw new Error('FILE_NOT_FOUND');
}

saveFile(fileName, blob) {
return Promise.resolve((this.storage[fileName] = blob));
async saveFile(fileName, blob) {
return (this.storage[fileName] = blob);
}

getFileWriter(fileName, mimeType) {
const fakeWriter = FileManager.getFakeFileWriter(mimeType, blob => {
async getFileWriter(fileName, mimeType) {
const save = blob => {
this.saveFile(fileName, blob);
});
return Promise.resolve(fakeWriter);
};
const fakeWriter = FileManager.getFakeFileWriter(mimeType, save);
return fakeWriter;
}
}



40 changes: 17 additions & 23 deletions src/scripts/yumjs/withStateHandlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,30 @@
* the root directory of this source tree.
*/

import { useReducer, useMemo } from 'react';
import { useReducer} from 'react';

const withStateHandlers = (initialValue, handlers) => (props = {}) => {
const withStateHandlers = (initialValue, handlers) => {
const actionTypes = Object.keys(handlers);

// note: action.type is function name, action.payload are function parameters
// handler = function [action.type](action.payload)
const reducer = (state, action) => ({
...state,
...handlers[action.type](state, props)(...action.payload),
...handlers[action.type](state, action.payload),
});

// see https://reactjs.org/docs/hooks-reference.html#usereducer
const [state, dispatch] = useReducer(
reducer,
// eslint-disable-next-line react-hooks/exhaustive-deps
typeof initialValue === 'function' ? useMemo(() => initialValue(props), []) : initialValue,
);

const boundHandlers = actionTypes.reduce(
(obj, type) =>
Object.assign(obj, {
[type]: (...payload) => {
if (payload !== undefined) dispatch({ type, payload });
},
}),
{},
);

return { ...props, ...state, ...boundHandlers };
const initialState =
typeof initialValue === 'function' ? initialValue() : initialValue;

const [state, dispatch] = useReducer(reducer, initialState);

const boundHandlers = actionTypes.reduce((obj, type) => {
obj[type] = (...payload) => {
if (payload !== undefined) dispatch({ type, payload });
};

return obj;
}, {});

return { ...state, ...boundHandlers };
};

export default withStateHandlers;
121 changes: 47 additions & 74 deletions src/serviceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,87 +16,60 @@

// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
const isLocalhost =
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/),
);
window.location.hostname === '[::1]' ||
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/);

function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
// eslint-disable-next-line no-param-reassign
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
// eslint-disable-next-line no-console
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.',
);

// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
// eslint-disable-next-line no-console
console.log('Content is cached for offline use.');
async function registerValidSW(swUrl, config) {
try {
const registration = await navigator.serviceWorker.register(swUrl);

registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (!installingWorker) return;

installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.',
);

config?.onUpdate?.(registration);
} else {
console.log('Content is cached for offline use.');

// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
config?.onSuccess?.(registration);
}
};
}
};
})
.catch(error => {
// eslint-disable-next-line no-console
console.error('Error during service worker registration:', error);
});
};
} catch (error) {
console.error('Error during service worker registration:', error);
}
}
// make it async for further fetch call
// simplified the catch block
// contentType check replaced with ?
// simplified if controls
async function checkValidServiceWorker(swUrl, config) {
try {
const response = await fetch(swUrl);
const contentType = response.headers.get('content-type');

function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
// eslint-disable-next-line no-console
console.log('No internet connection found. App is running in offline mode.');
});
if (response.status === 404 || contentType?.indexOf('javascript') === -1) {
const registration = await navigator.serviceWorker.ready;
await registration.unregister();
window.location.reload();
} else {
registerValidSW(swUrl, config);
}
} catch {
console.log('No internet connection found. App is running in offline mode.');
}
}

export function register(config) {
Expand All @@ -115,7 +88,7 @@ export function register(config) {

if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
checkValidServiceWorker(swUrl, config);

// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
Expand Down