Skip to content

Commit

Permalink
fix: handle absence of URLSearchParams support [CIVIL-1430]
Browse files Browse the repository at this point in the history
  • Loading branch information
tobek committed Feb 12, 2020
1 parent 28d926a commit 27e80d6
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/core/src/FeatureFlagService.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { getAllUrlSearchParam } from "@joincivil/utils";

export class FeatureFlagService {
public featureFlags: string[];
constructor(featureFlags?: string[]) {
const urlParams = new URLSearchParams(window.location.search);
this.featureFlags = (featureFlags || []).concat(urlParams.getAll("feature-flag"));
this.featureFlags = (featureFlags || []).concat(getAllUrlSearchParam("feature-flag"));
}
public featureEnabled(feature: string): boolean {
return this.featureFlags.includes(feature);
Expand Down
34 changes: 34 additions & 0 deletions packages/utils/src/browser.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,37 @@
export function getUrlSearchParam(name: string): string | null {
if (window.URLSearchParams) {
const urlParams = new URLSearchParams(window.location.search.slice(1));
return urlParams.get(name);
} else {
// Adapted from https://davidwalsh.name/query-string-javascript
const nameForRegex = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
const regex = new RegExp("[\\?&]" + nameForRegex + "=([^&#]*)");
const results = regex.exec(window.location.search);
return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, " "));
}
}

/** Returns array of all instances of a single URL search param e.g. searching for `"foo"` from `?foo=val1&foo=val2&bar=val3` would return `["val1", "val2"]`. */
export function getAllUrlSearchParam(name: string): string[] {
if (window.URLSearchParams) {
const urlParams = new URLSearchParams(window.location.search.slice(1));
return urlParams.getAll(name);
} else {
const nameForRegex = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
const regex = new RegExp("[\\?&]" + nameForRegex + "=([^&#]*)", "g");
const output = [];
let results: RegExpExecArray | null;
while (true) {
results = regex.exec(window.location.search);
if (!results) {
break;
}
output.push(decodeURIComponent(results[1].replace(/\+/g, " ")));
}
return output;
}
}

/** Copy given string to clipboard. Returns true if successful, false if failed. Should only fail on reaaally old browsers that we don't support. */
export function copyToClipboard(text: string): boolean {
const textArea = document.createElement("textarea");
Expand Down

0 comments on commit 27e80d6

Please sign in to comment.