Skip to content

Commit

Permalink
Merge pull request #71 from EastSun5566/feat/rewrite-demo
Browse files Browse the repository at this point in the history
refactor: rewrite hooks
  • Loading branch information
EastSun5566 committed Oct 31, 2022
2 parents 7b09448 + f3b3085 commit d228d8a
Show file tree
Hide file tree
Showing 10 changed files with 402 additions and 106 deletions.
4 changes: 3 additions & 1 deletion demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
"license": "MIT",
"homepage": "https://eastsun5566.github.io/cc-gram/",
"scripts": {
"dev": "rm -rf build && node scripts/start.js",
"dev": "node scripts/start.js",
"build": "node scripts/build.js",
"preview": "serve -s build",
"test": "node scripts/test.js",
"analyze": "source-map-explorer 'build/static/js/*.js'",
"deploy": "npm run build && gh-pages -d build"
Expand Down Expand Up @@ -152,6 +153,7 @@
"eslint-plugin-react-hooks": "^4.0.8",
"gh-pages": "^3.1.0",
"sass": "^1.51.0",
"serve": "^14.0.1",
"source-map-explorer": "^2.4.2"
}
}
15 changes: 15 additions & 0 deletions demo/public/index.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Google tag (gtag.js) -->
<script
async
src="https://www.googletagmanager.com/gtag/js?id=G-YGB6NCEQVB"
></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag("js", new Date());

gtag("config", "G-YGB6NCEQVB");
</script>

<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
Expand Down
5 changes: 2 additions & 3 deletions demo/src/App/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useState } from 'react';
import { CSSTransition } from 'react-transition-group';

import './App.scss';
Expand All @@ -9,10 +9,9 @@ import {
GithubCorner,
Note,
} from '../components';
import { useFilters } from '../hooks';

const App: React.FC = () => {
const [imageURL, setImageURL] = useFilters();
const [imageURL, setImageURL] = useState('');

return (
<>
Expand Down
23 changes: 10 additions & 13 deletions demo/src/components/Preview/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import React from 'react';

import './Preview.scss';

import { filter } from '../../filter';
import { useFilters, useDownloadImage } from '../../hooks';
import { useFilters, useDownloadFilterImage } from '../../hooks';

interface PreviewProps {
imageURL?: string;
Expand All @@ -15,21 +14,19 @@ export const Preview: React.FC<PreviewProps> = ({
imageURL,
onClear,
}) => {
const [selectedFilter, setSelectedFilter] = useFilters({
selectors: '#preview-image',
});
const { imageRef, download } = useDownloadImage({ downloadFileName: selectedFilter });

if (!imageURL) return null;

const { filter, selectedFilterName, setSelectedFilterName } = useFilters();
const { imageRef, download } = useDownloadFilterImage({ filter });

return (
<div className="preview">
<div className="image-container">
<img
id="preview-image"
src={imageURL}
data-filter={selectedFilter}
alt={selectedFilter.toUpperCase()}
data-filter={selectedFilterName}
alt={selectedFilterName.toUpperCase()}
ref={imageRef}
/>
<button
Expand All @@ -42,7 +39,7 @@ export const Preview: React.FC<PreviewProps> = ({
<button
type="button"
className="btn btn-download"
onClick={download}
onClick={() => download({ downloadFileName: selectedFilterName })}
>
<i className="fas fa-cloud-download-alt" />
</button>
Expand All @@ -53,10 +50,10 @@ export const Preview: React.FC<PreviewProps> = ({
filter.filterNames.map((filterName) => (
<figure
role="button"
className={selectedFilter === filterName ? 'selected' : ''}
className={selectedFilterName === filterName ? 'selected' : ''}
key={filterName}
onClick={() => setSelectedFilter(filterName)}
onKeyPress={() => setSelectedFilter(filterName)}
onClick={() => setSelectedFilterName(filterName)}
onKeyPress={() => setSelectedFilterName(filterName)}
>
<img
src={imageURL}
Expand Down
5 changes: 0 additions & 5 deletions demo/src/filter.ts

This file was deleted.

2 changes: 1 addition & 1 deletion demo/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './use-filters';
export * from './use-download-image';
export * from './use-download-filter-image';
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import { useRef } from 'react';
import { filter } from '../filter';
import { Filter } from '../../../dist/index.esm';

interface useDownloadImageOptions {
interface UseDownloadFilterImageOptions {
downloadFileName?: string;
filter: InstanceType<typeof Filter>;
}

export const useDownloadImage = ({
downloadFileName = 'download',
}: useDownloadImageOptions = {}): {
interface DownloadOptions {
downloadFileName?: string
}

export const useDownloadFilterImage = ({ filter }: UseDownloadFilterImageOptions): {
imageRef: React.RefObject<HTMLImageElement>;
download: () => void;
download(downloadOptions: DownloadOptions): Promise<void>;
} => {
const imageRef = useRef<HTMLImageElement>(null);

const download = async () => {
const download = async ({
downloadFileName = 'download',
} = {}) => {
const { current } = imageRef;
if (!current || !(current instanceof HTMLImageElement)) throw new TypeError('ref must be an image');

Expand All @@ -26,4 +31,4 @@ export const useDownloadImage = ({
return { imageRef, download };
};

export default useDownloadImage;
export default useDownloadFilterImage;
32 changes: 19 additions & 13 deletions demo/src/hooks/use-filters.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,31 @@
import { useState, useEffect } from 'react';
import { filter } from '../filter';

import { createFilter, Filter } from '../../../dist/index.esm';

interface useFiltersOptions {
initialValue?: string;
selectors?: string;
initialFilterName?: string;
}

export const useFilters = ({
initialValue = '',
selectors,
}: useFiltersOptions = {}): [
string,
React.Dispatch<React.SetStateAction<string>>
] => {
const [value, setValue] = useState(initialValue);
initialFilterName = '',
}: useFiltersOptions = {}): {
selectedFilterName: string;
setSelectedFilterName: React.Dispatch<React.SetStateAction<string>>;
filter: InstanceType<typeof Filter>;
} => {
const [selectedFilterName, setSelectedFilterName] = useState(initialFilterName);

const filter = createFilter({ init: false });

useEffect(() => {
filter.applyFilter(selectors);
}, [value]);
filter.applyFilter();
}, [selectedFilterName]);

return [value, setValue];
return {
selectedFilterName,
setSelectedFilterName,
filter,
};
};

export default useFilters;
106 changes: 53 additions & 53 deletions demo/src/serviceWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,58 +12,6 @@
// 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(
window.location.hostname === 'localhost'
// [::1] is the IPv6 localhost address.
|| window.location.hostname === '[::1]'
// 127.0.0.0/8 are considered localhost for IPv4.
|| window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,
),
);

type Config = {
onSuccess?: (registration: ServiceWorkerRegistration) => void;
onUpdate?: (registration: ServiceWorkerRegistration) => void;
};

export function register(config?: Config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(
process.env.PUBLIC_URL,
window.location.href,
);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}

window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

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

// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service '
+ 'worker. To learn more, visit https://bit.ly/CRA-PWA',
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}

function registerValidSW(swUrl: string, config?: Config) {
navigator.serviceWorker
.register(swUrl)
Expand Down Expand Up @@ -138,7 +86,59 @@ function checkValidServiceWorker(swUrl: string, config?: Config) {
});
}

export function unregister() {
const isLocalhost = Boolean(
window.location.hostname === 'localhost'
// [::1] is the IPv6 localhost address.
|| window.location.hostname === '[::1]'
// 127.0.0.0/8 are considered localhost for IPv4.
|| window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,
),
);

type Config = {
onSuccess?: (registration: ServiceWorkerRegistration) => void;
onUpdate?: (registration: ServiceWorkerRegistration) => void;
};

export function register(config?: Config): void {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(
process.env.PUBLIC_URL,
window.location.href,
);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}

window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

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

// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service '
+ 'worker. To learn more, visit https://bit.ly/CRA-PWA',
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}

export function unregister(): void {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then((registration) => {
registration.unregister();
Expand Down
Loading

0 comments on commit d228d8a

Please sign in to comment.