Skip to content

Commit

Permalink
Feature/1009 simplemde infra (#1013)
Browse files Browse the repository at this point in the history
* feat: fetch from devhub-cache-api-rs.fly.dev

* @Megha-Dev-19 WIP

* wip

* fmt

* wip

* events and devhub are ready to be reviewed

* feat: infra proposals

* fmt

* feat: rfps infra

* remove comments

* fix: spelling

* fix: spelling

* replace all nearqueryapi in devhub related to proposals and rfps

* devhub: simplemde, acceptedTerms, passing instance

* fix: devhub

* refactor events: deleted SimpleMDE and LinkedProposalsDropdown for both

* test: replace all references of queryapi in tests

* test: fix linkedProposals and simpleMDE test :)

* test: skip discussions test for now

* clean up SimpleMDE

* infra: SimpleMDE, LinkedDropdown rfp + proposal, Proposal + Rfp.jsx, remove fetchgraphql from common

* test: fix events test, 1. had to deploy events with new cors policy, 2. passing instance down to simplemde, 3. mock the test on the right api path.

* test: infra -- fix: should show correct linked RFP to a proposal in feed page

* test: infra -- fix: should create proposal and link an RFP

* remove comments

* test: @petersalomonsen fixed!

* fmt

* test: discussions test back in

* test: skip discussions test

* revert: changes to rfp comment test

* initial commit 1002

* fmt

* test for comparing local feed with production

* add events committee feed components + by-sort component

* fmt

* compare links in prod and local

* test: update events test

* add events committee feed components + by-sort component

* fmt

* test: update events test

* test: comment spec

* test: included some test from pr 982

* revert commit

* feat: simpleMDE to new api

* fmt

* feat: linkedproposaldropdown to new api

* fmt

* test: proposal autolink

* fix: simplemde + test

---------

Co-authored-by: Peter Salomonsen <[email protected]>
  • Loading branch information
Tguntenaar and petersalomonsen authored Dec 9, 2024
1 parent 4c34de6 commit 41fcadb
Show file tree
Hide file tree
Showing 6 changed files with 158 additions and 136 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ const Comment = ({ commentItem }) => {
};
const content = JSON.parse(Social.get(item.path, blockHeight) ?? "null");
const link = `https://${instanceAccount}.page/proposal/${proposalId}?accountId=${accountId}&blockHeight=${blockHeight}`;
const hightlightComment =
const highlightComment =
parseInt(props.blockHeight ?? "") === blockHeight &&
props.accountId === accountId;

Expand All @@ -188,7 +188,7 @@ const Comment = ({ commentItem }) => {
</div>
<CommentContainer
id={`${accountId.replace(/[^a-z0-9]/g, "")}${blockHeight}`}
style={{ border: hightlightComment ? "2px solid black" : "" }}
style={{ border: highlightComment ? "2px solid black" : "" }}
className="rounded-2 flex-1"
>
<Header className="d-flex gap-3 align-items-center p-2 px-3">
Expand Down
3 changes: 2 additions & 1 deletion instances/infrastructure-committee.near/aliases.mainnet.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
"REPL_RFP_INDEXER_QUERY_NAME": "polyprogrammist_near_devhub_ic_v1_rfp_snapshots",
"REPL_PROPOSAL_FEED_INDEXER_QUERY_NAME": "polyprogrammist_near_devhub_ic_v1_proposals_with_latest_snapshot",
"REPL_PROPOSAL_QUERY_NAME": "polyprogrammist_near_devhub_ic_v1_proposal_snapshots",
"REPL_INDEXER_HASURA_ROLE": "polyprogrammist_near"
"REPL_INDEXER_HASURA_ROLE": "polyprogrammist_near",
"REPL_CACHE_URL": "https://infra-cache-api-rs.fly.dev"
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,9 @@ State.init({
message: props.data,
});

const profilesData = Social.get("*/profile/name", "final");
const followingData = Social.get(
`${context.accountId}/graph/follow/**`,
"final"
);
const profilesData = Social.get("*/profile/name", "final") ?? {};
const followingData =
Social.get(`${context.accountId}/graph/follow/**`, "final") ?? {};

// SIMPLEMDE CONFIG //
const fontFamily = props.fontFamily ?? "sans-serif";
Expand All @@ -33,37 +31,9 @@ const showProposalIdAutoComplete = props.showProposalIdAutoComplete ?? false;
const showRfpIdAutoComplete = props.showRfpIdAutoComplete ?? false;
const autoFocus = props.autoFocus ?? false;

const proposalQueryName = "${REPL_PROPOSAL_FEED_INDEXER_QUERY_NAME}";
const proposalLink = getLinkUsingCurrentGateway(
`${REPL_INFRASTRUCTURE_COMMITTEE}/widget/app?page=proposal&id=`
);
const proposalQuery = `query GetLatestSnapshot($offset: Int = 0, $limit: Int = 10, $where: ${proposalQueryName}_bool_exp = {}) {
${proposalQueryName}(
offset: $offset
limit: $limit
order_by: {proposal_id: desc}
where: $where
) {
name
proposal_id
}
}`;

const rfpQueryName = "${REPL_RFP_FEED_INDEXER_QUERY_NAME}";
const rfpLink = getLinkUsingCurrentGateway(
`${REPL_INFRASTRUCTURE_COMMITTEE}/widget/app?page=rfp&id=`
);
const rfpQuery = `query GetLatestSnapshot($offset: Int = 0, $limit: Int = 10, $where: ${rfpQueryName}_bool_exp = {}) {
${rfpQueryName}(
offset: $offset
limit: $limit
order_by: {rfp_id: desc}
where: $where
) {
rfp_id
name
}
}`;

const code = `
<!doctype html>
Expand Down Expand Up @@ -146,12 +116,8 @@ let codeMirrorInstance;
let isEditorInitialized = false;
let followingData = {};
let profilesData = {};
let proposalQuery = '';
let proposalLink = '';
let proposalQueryName = '';
let rfpQuery = '';
let rfpLink = '';
let rfpQueryName = '';
let showAccountAutoComplete = ${showAccountAutoComplete};
let showProposalIdAutoComplete = ${showProposalIdAutoComplete};
let showRfpIdAutoComplete = ${showRfpIdAutoComplete}
Expand Down Expand Up @@ -206,12 +172,11 @@ function getSuggestedAccounts(term) {
return results;
}
async function asyncFetch(endpoint, { method, headers, body }) {
async function asyncFetch(endpoint, { method, headers }) {
try {
const response = await fetch(endpoint, {
method: method,
headers: headers,
body: body
});
if (!response.ok) {
Expand All @@ -235,89 +200,36 @@ function extractNumbers(str) {
return numbers;
};
function searchCacheApi(entity, searchProposalId) {
let searchInput = encodeURI(searchProposalId);
let searchUrl = "https://infra-cache-api-rs.fly.dev/"+entity+"/search/" + searchInput;
return asyncFetch(searchUrl, {
method: "GET",
headers: {
accept: "application/json",
},
}).catch((error) => {
console.log("Error searching cache api", error);
});
}
async function getSuggestedRfps(id) {
let results = [];
const variables = {
limit: 3,
offset: 0,
where: {},
};
if (id) {
const rfpId = extractNumbers(id);
if (rfpId) {
variables["where"] = { rfp_id: { _eq: id } };
} else {
variables["where"] = {
_or: [
{ name: { _iregex: id } },
{ summary: { _iregex: id } },
{ description: { _iregex: id} },
]
};
}
const searchResults = await searchCacheApi('rfp', id);
results = searchResults?.records || [];
}
await asyncFetch("https://near-queryapi.api.pagoda.co/v1/graphql", {
method: "POST",
headers: { "x-hasura-role": "${REPL_INDEXER_HASURA_ROLE}" },
body: JSON.stringify({
query: rfpQuery,
variables: variables,
operationName: "GetLatestSnapshot",
}),
})
.then((res) => {
const rfps =
res?.data?.[
rfpQueryName
];
results = rfps;
})
.catch((error) => {
console.error(error);
});
return results;
};
async function getSuggestedProposals(id) {
let results = [];
const variables = {
limit: 3,
offset: 0,
where: {},
};
if (id) {
const proposalId = extractNumbers(id);
if (proposalId) {
variables["where"] = { proposal_id: { _eq: id } };
} else {
variables["where"] = {
_or: [
{ name: { _iregex: id } },
{ summary: { _iregex: id } },
{ description: { _iregex: id} },
]
};
}
const searchResults = await searchCacheApi('proposals', id);
results = searchResults?.records || [];
}
await asyncFetch("https://near-queryapi.api.pagoda.co/v1/graphql", {
method: "POST",
headers: { "x-hasura-role": "${REPL_INDEXER_HASURA_ROLE}" },
body: JSON.stringify({
query: proposalQuery,
variables: variables,
operationName: "GetLatestSnapshot",
}),
})
.then((res) => {
const proposals =
res?.data?.[
proposalQueryName
];
results = proposals;
})
.catch((error) => {
console.error(error);
});
return results;
};
Expand Down Expand Up @@ -468,7 +380,7 @@ if (showAccountAutoComplete) {
});
});
}
// show dropwdown only when @ is at first place or when there is a space before @
// show dropdown only when @ is at first place or when there is a space before @
if (!mentionToken && (token.string === "@" && cursor.ch === 1 || token.string === "@" && cm.getTokenAt({line:cursor.line, ch: cursor.ch - 1}).string == ' ')) {
mentionToken = token;
mentionCursorStart = cursor;
Expand Down Expand Up @@ -505,6 +417,7 @@ if (showProposalIdAutoComplete) {
let proposalId;
let referenceCursorStart;
const dropdown = document.getElementById("referencedropdown");
// Create loader element once and store it
const loader = document.createElement('div');
loader.className = 'loader';
loader.textContent = 'Loading...';
Expand Down Expand Up @@ -572,7 +485,7 @@ if (showProposalIdAutoComplete) {
}
}
// show dropwdown only when there is space before # or it's first char
// show dropdown only when there is space before # or it's first char
if (!proposalId && (token.string === "#" && cursor.ch === 1 || token.string === "#" && cm.getTokenAt({line:cursor.line, ch: cursor.ch - 1}).string == ' ')) {
proposalId = token;
referenceCursorStart = cursor;
Expand Down Expand Up @@ -621,26 +534,12 @@ window.addEventListener("message", (event) => {
if (event.data.profilesData) {
profilesData = JSON.parse(event.data.profilesData);
}
if (event.data.proposalQuery) {
proposalQuery = event.data.proposalQuery;
}
if (event.data.proposalQueryName) {
proposalQueryName = event.data.proposalQueryName;
}
if (event.data.proposalLink) {
proposalLink = event.data.proposalLink;
}
if (event.data.rfpQuery) {
rfpQuery = event.data.rfpQuery;
}
if (event.data.rfpQueryName) {
rfpQueryName = event.data.rfpQueryName;
}
if (event.data.rfpLink) {
rfpLink = event.data.rfpLink;
}
});
</script>
</body>
Expand All @@ -660,13 +559,9 @@ return (
content: props.data?.content ?? "",
followingData,
profilesData: JSON.stringify(profilesData),
proposalQuery: proposalQuery,
proposalQueryName: proposalQueryName,
handler: props.data.handler,
proposalLink: proposalLink,
rfpQuery: rfpQuery,
rfpQueryName: rfpQueryName,
rfpLink: rfpLink,
handler: props.data.handler,
}}
onMessage={(e) => {
switch (e.handler) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ return {
rfpFeedIndexerQueryName:
"polyprogrammist_near_devhub_ic_v1_rfps_with_latest_snapshot",
indexerHasuraRole: "polyprogrammist_near",
cacheUrl: "${REPL_CACHE_URL}",
isInfra: true,
proposalFeedAnnouncement,
aavailableCategoryOptions: getGlobalLabels(),
availableCategoryOptions: getGlobalLabels(),
};
49 changes: 49 additions & 0 deletions instances/infrastructure-committee.near/widget/core/common.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,53 @@ const PROPOSAL_TIMELINE_STATUS = {
};

const QUERYAPI_ENDPOINT = `https://near-queryapi.api.pagoda.co/v1/graphql`;
const cacheUrl = "https://infra-cache-api-rs.fly.dev";

/**
* Get proposals or rfps from cache api
* @param {proposals | rfps} entity
* @param {order, limit, offset, author_id, stage, category} variables
* @returns result.records, result.total_records, result.total_pages
*/
function fetchCacheApi(entity, variables) {
console.log("Fetching cache api", variables);

let fetchUrl = `${cacheUrl}/${entity}?order=${variables.order}&limit=${variables.limit}&offset=${variables.offset}`;

if (variables.author_id) {
fetchUrl += `&filters.author_id=${variables.author_id}`;
}
if (variables.stage) {
fetchUrl += `&filters.stage=${variables.stage}`;
}
if (variables.category) {
// Devhub uses category, infra uses labels
fetchUrl += `&filters.labels=${variables.category}`;
}
console.log("Fetching.. from infra common", fetchUrl);
return asyncFetch(fetchUrl, {
method: "GET",
headers: {
accept: "application/json",
},
}).catch((error) => {
console.log("Error fetching cache api", error);
});
}

function searchCacheApi(entity, searchTerm) {
let searchInput = encodeURI(searchTerm);
let searchUrl = `${cacheUrl}/${entity}/search/${searchInput}`;

return asyncFetch(searchUrl, {
method: "GET",
headers: {
accept: "application/json",
},
}).catch((error) => {
console.log(`Error searching cache api in entity ${entity}:`, error);
});
}

async function fetchGraphQL(operationsDoc, operationName, variables) {
return asyncFetch(QUERYAPI_ENDPOINT, {
Expand Down Expand Up @@ -76,4 +123,6 @@ return {
isNumber,
PROPOSALS_APPROVED_STATUS_ARRAY,
getLinkUsingCurrentGateway,
searchCacheApi,
fetchCacheApi,
};
Loading

0 comments on commit 41fcadb

Please sign in to comment.