Skip to content

Commit

Permalink
update assets url after mount :prerelease
Browse files Browse the repository at this point in the history
  • Loading branch information
foxundermoon committed Jan 28, 2020
1 parent b2fec23 commit f049be0
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 5 deletions.
61 changes: 57 additions & 4 deletions packages/transparent-info-app/components/ipfs/Env.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,66 @@
import { useState, useEffect } from 'react';
import { ipfsGateways } from '../../src/config';

export let baseUrl = '';

type MediaElement = HTMLImageElement | HTMLAudioElement | HTMLVideoElement;

interface WithSrc {
src: string;
}

function isIpfsResource(src: string) {
return /\/ip[fn]s\//.test(src);
}

function checkReplaceSrc(e: WithSrc) {
if (e.src && isIpfsResource(e.src)) {
e.src = `${ipfsGateways[0]}${e.src}`;
}
}

function replaceAssetsSrc() {
document.querySelectorAll('script').forEach(e => {
if (e.src) {
if (isIpfsResource(e.src)) {
e.src = e.src.replace(/\/ip[fn]s\/[^\/]+/, baseUrl);
} else {
e.src = `${baseUrl}${e.src}`;
}
}
});

document.querySelectorAll('link').forEach(e => {
if (e.href) {
if (isIpfsResource(e.href)) {
e.href = e.href.replace(/\/ip[fn]s\/[^\/]+/, baseUrl);
} else {
e.href = `${baseUrl}${e.href}`;
}
}
});
}

export function getIpfsBasePath(urlOrPath: string) {
const groups = /(\/ip[fn]s\/[^\/]+)/.exec(urlOrPath);
if (groups && groups.length > 0) {
return groups[1];
}
return '';
}

function currentAssetsPath() {
const path = document.location.pathname;
baseUrl = getIpfsBasePath(path);
}

export default () => {
useEffect(() => {
if (!/ip[fn]s\//.test(window.location.href)) {
currentAssetsPath();
replaceAssetsSrc();
if (!isIpfsResource(window.location.href)) {
// tmp chose first
document.querySelectorAll('img').forEach(e => {
e.src = `${ipfsGateways[0]}${e.src}`;
});
document.querySelectorAll('img').forEach(checkReplaceSrc);
}
}, []);

Expand Down
7 changes: 6 additions & 1 deletion packages/transparent-info-app/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@ const withMDX = require('@next/mdx')({
},
});

const assetPrefix = process.env['ASSETS_PREFIX'] || '/';

module.exports = withMDX({
pageExtensions: ['js', 'jsx', 'md', 'mdx', 'tsx'],
assetPrefix: '/ipns/dncov.fox.mn/',
assetPrefix: assetPrefix,
env: {
ASSETS_PREFIX: assetPrefix,
},
// assetPrefix: '/ipns/Qmd3HzpnpSsLeUQF2mJEXn24a1yYo2LTaQyoq4mwxkse1Z/',
});

0 comments on commit f049be0

Please sign in to comment.