Skip to content

Commit

Permalink
feat: Share function & clipboard copying
Browse files Browse the repository at this point in the history
  • Loading branch information
johnflank committed Mar 24, 2022
1 parent 9561806 commit ab79eaf
Showing 1 changed file with 45 additions and 8 deletions.
53 changes: 45 additions & 8 deletions src/pages/config/config-details.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useNavigate } from "react-router-dom";
import {
decodeUrlSearchParams,
updateParams
} from "../../components/Canary/url";

import { SearchLayout } from "../../components/Layout";
import jsonString from "../../data/sampleConfig.json";

Expand All @@ -14,16 +20,49 @@ export function ConfigDetailsPage() {
const navigate = useNavigate();
const [checked, setChecked] = useState({});

useEffect(() => {
const { selected } = decodeUrlSearchParams(window.location.search);
if (selected) {
const decoded = selected.split(",").map((str) => parseInt(str, 10));
const newChecked = {};
decoded.forEach((lineNum) => {
newChecked[lineNum] = linesArrayWithIndex[lineNum];
});
setChecked(newChecked);
}
}, []);

const getSelectedEncodedURL = () => {
const selectedArr = Object.keys(checked);
const encoded = encodeURIComponent(selectedArr);
return encoded;
};

const handleCheck = (index, value) => {
const newChecked = { ...checked };
if (value) {
const newChecked = { ...checked };
newChecked[index] = linesArrayWithIndex[index];
setChecked(newChecked);
} else {
const newChecked = { ...checked };
delete newChecked[index];
setChecked(newChecked);
}

updateParams({
selected: Object.keys(newChecked).reduce(
(acc, curr) => `${acc}${acc.length > 0 ? "," : ""}${curr}`,
""
)
});
};

const handleShare = () => {
const { origin, pathname } = window.location;
const copyString = `${origin}${pathname}?selected=${getSelectedEncodedURL()}`;
navigator.clipboard.writeText(copyString).then(() => {
toast("Copied to clipboard");
});
};

return (
Expand All @@ -45,7 +84,9 @@ export function ConfigDetailsPage() {
<button
className="border rounded-md px-3 py-1 mr-2 text-sm"
type="button"
onClick={() => {}}
onClick={() => {
handleShare();
}}
>
Share
</button>
Expand All @@ -59,16 +100,12 @@ export function ConfigDetailsPage() {
</>
)}
</div>

<div className="flex flex-col w-full">
{Object.entries(linesArrayWithIndex).map(([lineIndex, line]) => (
<div key={lineIndex} className="border flex flex-row">
<div className="px-1 flex items-center justify-center">
<input
value={Object.prototype.hasOwnProperty.call(
checked,
lineIndex
)}
checked={checked[lineIndex]}
type="checkbox"
onChange={(e) => handleCheck(lineIndex, e.target.checked)}
/>
Expand Down

0 comments on commit ab79eaf

Please sign in to comment.