Skip to content
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

refactor: change order of attributes and script variables #889

Merged
merged 1 commit into from
Sep 14, 2023
Merged
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
37 changes: 23 additions & 14 deletions packages/snap-toolbox/src/getContext/getContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,17 @@ export function getContext(evaluate: string[] = [], script?: HTMLScriptElement |

const siteIdString = 'siteId';

const variables: ContextVariables = {};
const attributeVariables: ContextVariables = {};

// grab element attributes and put into variables
Object.values(scriptElem.attributes).map((attr) => {
const name = attr.nodeName;
if (evaluate.includes(name)) {
attributeVariables[name] = scriptElem.getAttribute(name);
}
});

const scriptVariables: ContextVariables = {};

// evaluate text and put into variables
evaluate?.forEach((name) => {
Expand All @@ -45,21 +55,13 @@ export function getContext(evaluate: string[] = [], script?: HTMLScriptElement |
return ${name};
`);

variables[name] = fn();
});

// grab element attributes and put into variables
Object.values(scriptElem.attributes).map((attr) => {
const name = attr.nodeName;
if (evaluate.includes(name)) {
variables[name] = scriptElem.getAttribute(name);
}
scriptVariables[name] = fn();
});

// remove undefined entries
Object.keys(variables).forEach((key) => {
if (typeof variables[key] === 'undefined') delete variables[key];
});
const variables = {
...removeUndefined(attributeVariables),
...removeUndefined(scriptVariables),
};

if (evaluate.includes(siteIdString)) {
// if we didnt find a siteId in the context, lets grab the id from the src url.
Expand All @@ -73,3 +75,10 @@ export function getContext(evaluate: string[] = [], script?: HTMLScriptElement |

return variables;
}

function removeUndefined(variables: ContextVariables) {
Object.keys(variables).forEach((key) => {
if (typeof variables[key] === 'undefined') delete variables[key];
});
return variables;
}
Loading