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

URL bar improvements #526

Merged
merged 35 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
a66e01e
Add URL history to navigation
p-malecki Aug 30, 2024
9c787f4
Show full name of URLs in tooltips
p-malecki Aug 30, 2024
ce2dc18
Extend full name of URLs in list item instead of tooltips
p-malecki Sep 2, 2024
967644e
Upgrade spliting long url labels in URL bar
p-malecki Sep 3, 2024
def9ac1
Add recent URLs list to SelectUrl
p-malecki Sep 3, 2024
3e9f547
Add scrolling to SelectUrl
p-malecki Sep 3, 2024
20113ce
Add recent URLs list to UrlBar
p-malecki Sep 3, 2024
01aaa91
Make Select.Trigger more responsive
p-malecki Sep 4, 2024
0388d0b
Change UrlSelect style
p-malecki Sep 4, 2024
4ac59a3
Minor changes
p-malecki Sep 4, 2024
d47c878
Reformat
p-malecki Sep 4, 2024
3086be6
Move reset logic to useEffect with changing resetKey prop
p-malecki Sep 4, 2024
d6b7fe0
Refactor
p-malecki Sep 4, 2024
22c35f1
Simplify url bar css, remove splitLines
p-malecki Sep 5, 2024
0e70dbd
Change reset logic
p-malecki Sep 5, 2024
809cdce
Add params from navigationDescriptor to navigationData
p-malecki Sep 5, 2024
739dcc3
Revert "Add params from navigationDescriptor to navigationData"
p-malecki Sep 5, 2024
544e920
Add ExpoRouter to dependency checks
p-malecki Sep 6, 2024
5dd5272
Change goHome
p-malecki Sep 6, 2024
7efd05b
Fix reset logic and changing urls
p-malecki Sep 6, 2024
c003b87
Remove consol log
p-malecki Sep 6, 2024
e0e5a6d
Update NiceButton.stories.jsx
p-malecki Sep 6, 2024
476ea1b
Remove project from UrlBar props
p-malecki Sep 6, 2024
68ad7ca
Change isOptional in dependenciesProvider
p-malecki Sep 9, 2024
57ff8d3
Update packages/vscode-extension/src/dependency/DependencyManager.ts
p-malecki Sep 9, 2024
fa0a164
Simplify isExpoRouterProject
p-malecki Sep 9, 2024
663d217
Use requireNoCache in isExpoRouterProject
p-malecki Sep 9, 2024
d144cb2
Use reloadMetro in goHome for non expo-router projects
p-malecki Sep 9, 2024
33f98bc
Fix URL changes in useEffect
p-malecki Sep 9, 2024
6c51a81
Fix storing dynamic paths twice in url history on go back
p-malecki Sep 10, 2024
6972b78
Remove consol.log
p-malecki Sep 10, 2024
4ef0333
Merge branch 'main' into @p-malecki/urlbar-enhance
p-malecki Sep 11, 2024
7640e6b
Fix in expo router project detection to scan devDependencies
p-malecki Sep 11, 2024
7e89e30
Add comment to isExpoRouterProject
p-malecki Sep 11, 2024
3f7447c
Rename label in DiagnosticView
p-malecki Sep 11, 2024
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
2 changes: 1 addition & 1 deletion packages/vscode-extension/src/common/Project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@

// important: order of values in this enum matters
export enum StartupMessage {
InitializingDevice = "Initializing device",

Check warning on line 37 in packages/vscode-extension/src/common/Project.ts

View workflow job for this annotation

GitHub Actions / check

Enum Member name `InitializingDevice` must match one of the following formats: camelCase
StartingPackager = "Starting packager",
BootingDevice = "Booting device",
Building = "Building",
Expand Down Expand Up @@ -106,7 +106,7 @@
getProjectState(): Promise<ProjectState>;
reload(type: ReloadAction): Promise<boolean>;
restart(forceCleanBuild: boolean): Promise<void>;
goHome(): Promise<void>;
goHome(homeUrl: string): Promise<void>;
selectDevice(deviceInfo: DeviceInfo): Promise<void>;
updatePreviewZoomLevel(zoom: ZoomLevelType): Promise<void>;

Expand Down
40 changes: 40 additions & 0 deletions packages/vscode-extension/src/dependency/DependencyManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { Platform } from "../utilities/platform";
const MIN_REACT_NATIVE_VERSION_SUPPORTED = "0.71.0";
const MIN_EXPO_SDK_VERSION_SUPPORTED = "49.0.0";
const MIN_STORYBOOK_VERSION_SUPPORTED = "5.2.0";
const MIN_EXPO_ROUTER_VERSION_SUPPORTED = "0.0.0";

export class DependencyManager implements Disposable {
private disposables: Disposable[] = [];
Expand Down Expand Up @@ -67,6 +68,10 @@ export class DependencyManager implements Disposable {
Logger.debug("Received checkNodeModulesInstalled command.");
this.checkNodeModulesInstalled();
return;
case "checkExpoRouterInstalled":
Logger.debug("Received checkExpoRouterInstalled command.");
this.checkExpoRouterInstalled();
return;
case "checkStorybookInstalled":
Logger.debug("Received checkStorybookInstalled command.");
this.checkStorybookInstalled();
Expand Down Expand Up @@ -315,6 +320,27 @@ export class DependencyManager implements Disposable {
return installed;
}

public async checkExpoRouterInstalled() {
const status = checkMinDependencyVersionInstalled(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this function alone does not give as information if project uses expo router or not

"expo-router",
MIN_EXPO_ROUTER_VERSION_SUPPORTED
);

const installed = status === "installed";

this.webview.postMessage({
command: "isExpoRouterInstalled",
data: {
installed,
info: "Whether supported version of Expo Router is installed.",
error: undefined,
isOptional: !isExpoRouterProject(),
},
});
Logger.debug(`Minimum Expo version installed:`, installed);
return installed;
}

public async checkStorybookInstalled() {
const status = checkMinDependencyVersionInstalled(
"@storybook/react-native",
Expand All @@ -328,6 +354,7 @@ export class DependencyManager implements Disposable {
installed,
info: "Whether Storybook is installed.",
error: undefined,
isOptional: true,
},
});
Logger.debug("Storybook installed:", installed);
Expand Down Expand Up @@ -435,3 +462,16 @@ export function checkMinDependencyVersionInstalled(dependency: string, minVersio
export async function checkAndroidEmulatorExists() {
return fs.existsSync(EMULATOR_BINARY);
}

export function isExpoRouterProject() {
try {
const appRoot = getAppRootFolder();
const packageJson = require(path.join(appRoot, "package.json"));
Copy link
Collaborator

@filip131311 filip131311 Sep 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

requireNoCache

const hasExpoRouter = Object.values<string>(packageJson.dependencies).some(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(dependency) => dependency === "expo-router"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can expo router ever be a dev dependency?

);
return hasExpoRouter;
} catch (e) {
return false;
}
}
10 changes: 8 additions & 2 deletions packages/vscode-extension/src/project/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export class Project

private detectedFingerprintChange: boolean;

private expoRouterInstalled: boolean;
private storybookInstalled: boolean;

private fileWatcher: Disposable;
Expand Down Expand Up @@ -90,6 +91,7 @@ export class Project
this.trySelectingInitialDevice();
this.deviceManager.addListener("deviceRemoved", this.removeDeviceListener);
this.detectedFingerprintChange = false;
this.expoRouterInstalled = false;
this.storybookInstalled = false;

this.fileWatcher = watchProjectFiles(() => {
Expand Down Expand Up @@ -236,8 +238,10 @@ export class Project
}
}

public async goHome() {
await this.reloadMetro();
public async goHome(homeUrl: string) {
if (this.expoRouterInstalled) {
await this.openNavigation(homeUrl);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if it's not installed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It that case we reload metro. I've changed it.

}

//#region Session lifecycle
Expand Down Expand Up @@ -316,6 +320,8 @@ export class Project
[installNodeModules]
);

Logger.debug("Checking expo router");
this.expoRouterInstalled = await this.dependencyManager.checkExpoRouterInstalled();
Logger.debug("Checking storybook");
this.storybookInstalled = await this.dependencyManager.checkStorybookInstalled();
}
Expand Down
99 changes: 59 additions & 40 deletions packages/vscode-extension/src/webview/components/UrlBar.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
import { useEffect, useState } from "react";
import IconButton from "./shared/IconButton";
import { ProjectInterface, ProjectState } from "../../common/Project";
import UrlSelect from "./UrlSelect";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { useEffect, useState, useMemo } from "react";
import { useProject } from "../providers/ProjectProvider";
import UrlSelect, { UrlItem } from "./UrlSelect";
import { IconButtonWithOptions } from "./IconButtonWithOptions";
import IconButton from "./shared/IconButton";

interface UrlBarProps {
project: ProjectInterface;
disabled?: boolean;
}

interface ReloadButtonProps {
project: ProjectInterface;
disabled: boolean;
}

function ReloadButton({ project, disabled }: ReloadButtonProps) {
function ReloadButton({ disabled }: { disabled: boolean }) {
const { project } = useProject();
return (
<IconButtonWithOptions
onClick={() => project.restart(false)}
Expand All @@ -35,64 +25,93 @@ function ReloadButton({ project, disabled }: ReloadButtonProps) {
);
}

function UrlBar({ project, disabled }: UrlBarProps) {
const [urlList, setUrlList] = useState<{ name: string; id: string }[]>([]);
function UrlBar({ disabled }: { disabled?: boolean }) {
const { project } = useProject();

const MAX_URL_HISTORY_SIZE = 20;
const MAX_RECENT_URL_SIZE = 5;

const [urlList, setUrlList] = useState<UrlItem[]>([]);
const [recentUrlList, setRecentUrlList] = useState<UrlItem[]>([]);
const [urlHistory, setUrlHistory] = useState<string[]>([]);

useEffect(() => {
function moveAsMostRecent(urls: UrlItem[], newUrl: UrlItem) {
return [newUrl, ...urls.filter((record) => record.id !== newUrl.id)];
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe it would be better to write it like this:

const result = urls.filter((record) => record.id !== newUrl.id);
result.unshift(newUrl);
return result

I made a simple benchmark to check the approaches:

let testCases = new Array(1000).fill(0).map(()=>{
    const list = new Array(1000).fill(0);

    return list.map((e,i)=>{
        return i;
    });
});

const movedURL = 560; 
let start = performance.now();
for ( let testCase of testCases){
    const newTestCase = [ movedURL, ...testCase.filter((element)=>element !==movedURL)];
}
let end = performance.now();


testCases = new Array(1000).fill(0).map(()=>{
    const list = new Array(1000).fill(0);

    return list.map((e,i)=>{
        return i;
    });
});
console.log("old approach",start - end);
 start = performance.now();

for ( let testCase of testCases){
    const filtered = testCase.filter((element)=>element !==movedURL);
    filtered.unshift(movedURL);
    const newTestCase = filtered;
}

end = performance.now();

console.log("new approach",start - end);

and got following results:
Screenshot 2024-09-09 at 17 55 45

Copy link
Member

@jakub-gonet jakub-gonet Sep 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't agree, trading 2ms of performance for worse readability isn't worth it. Especially when you tested it on 1k long list, we won't get anywhere that list length ever.


function handleNavigationChanged(navigationData: { displayName: string; id: string }) {
const newRecord = { name: navigationData.displayName, id: navigationData.id };
setUrlList((urlList) => [
newRecord,
...urlList.filter((record) => record.id !== newRecord.id),
]);
if (navigationData.displayName === "") {
return;
}

const newRecord: UrlItem = {
name: navigationData.displayName,
id: navigationData.id,
};
const isNotInHistory = urlHistory.length === 0 || urlHistory[0] !== newRecord.id;

setUrlList((currentUrlList) => moveAsMostRecent(currentUrlList, newRecord));
setRecentUrlList((currentRecentUrlList) => {
const updatedRecentUrls = moveAsMostRecent(currentRecentUrlList, newRecord);
return updatedRecentUrls.slice(0, MAX_RECENT_URL_SIZE);
});

if (isNotInHistory) {
setUrlHistory((currentUrlHistoryList) => {
const updatedUrlHistory = [newRecord.id, ...currentUrlHistoryList];
return updatedUrlHistory.slice(0, MAX_URL_HISTORY_SIZE);
});
}
}

project.addListener("navigationChanged", handleNavigationChanged);
const handleProjectReset = (e: ProjectState) => {
if (e.status === "starting") {
setUrlList([]);
}
};
project.addListener("projectStateChanged", handleProjectReset);
return () => {
project.removeListener("navigationChanged", handleNavigationChanged);
project.removeListener("projectStateChanged", handleProjectReset);
};
}, []);

const sortedUrlList = useMemo(() => {
return [...urlList].sort((a, b) => a.name.localeCompare(b.name));
}, [urlList]);

return (
<>
<IconButton
tooltip={{
label: "Go back",
side: "bottom",
}}
disabled={disabled || urlList.length < 2}
disabled={disabled || urlHistory.length < 2}
onClick={() => {
project.openNavigation(urlList[1].id);
// remove first item from the url list
setUrlList((urlList) => urlList.slice(1));
setUrlHistory((prevUrlHistory) => {
const newUrlHistory = prevUrlHistory.slice(1);
project.openNavigation(newUrlHistory[0]);
return newUrlHistory;
});
}}>
<span className="codicon codicon-arrow-left" />
</IconButton>
<ReloadButton project={project} disabled={disabled ?? false} />
<ReloadButton disabled={disabled ?? false} />
<IconButton
onClick={() => {
project.goHome();
setUrlList([]);
project.goHome("/{}");
}}
tooltip={{
label: "Go to main screen",
side: "bottom",
}}
disabled={disabled || urlList.length == 0}>
disabled={disabled || urlList.length < 2}>
<span className="codicon codicon-home" />
</IconButton>
<UrlSelect
onValueChange={(value: string) => {
project.openNavigation(value);
}}
items={urlList}
recentItems={recentUrlList}
items={sortedUrlList}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're filtering out URLs if they have no name, do we want to store them then?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When changing from a preview to another URL, two route changes happen: {displayName: '', id: '{}'} and {displayName: '/', id: '/{}'}. We skip storing the first route with an empty displayName to prevent saving home URL entries twice.

value={urlList[0]?.id}
disabled={disabled || urlList.length < 1}
disabled={disabled || urlList.length < 2}
/>
</>
);
Expand Down
46 changes: 38 additions & 8 deletions packages/vscode-extension/src/webview/components/UrlSelect.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@

.url-select-trigger {
box-sizing: border-box;
display: inline-flex;
display: inline;
align-items: center;
padding: 0 10px;
font-size: 13px;
line-height: 1;
overflow: hidden;
cursor: pointer;
height: 36px;
border: 0px solid transparent;
Expand All @@ -18,8 +19,7 @@
color: var(--swm-url-select);
background-color: var(--swm-url-select-background);
user-select: none;
/* min-width: var(--url-select-min-width); */
max-width: var(--url-select-max-width);
min-width: var(--url-select-min-width);
}
.url-select-trigger:hover {
background-color: var(--swm-url-select-hover-background);
Expand All @@ -43,20 +43,39 @@
border-radius: 18px 18px 18px 18px;
transform: translateY(4px);
padding-bottom: 4px;
min-width: var(--url-select-min-width);
max-width: var(--url-select-max-width);
max-width: var(--radix-select-content-available-width);
max-height: var(--radix-select-content-available-height);
}

.url-select-viewport {
padding: 6px;
}

.url-select-scroll {
display: flex;
justify-content: center;
align-items: center;
}

.url-select-label {
padding: 0 4px 0 4px;
font-size: 13px;
line-height: 20px;
}

.url-select-separator {
height: 1px;
background-color: var(--swm-url-select-separator);
margin: 5px;
}

.url-select-item {
font-size: 13px;
line-height: 1;
line-height: 1.2;
display: flex;
align-items: center;
height: 30px;
min-height: 30px;
height: auto;
padding: 0 4px;
position: relative;
border-radius: 4px;
Expand All @@ -71,5 +90,16 @@
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
max-width: 240px;
max-width: calc(var(--radix-select-content-available-width) - 15px);
}
.url-select-item:hover .url-select-item-text {
white-space: normal;
padding-top: 6px;
padding-bottom: 6px;
}

@media (width <= 400px) {
.url-select-trigger {
min-width: 0;
}
}
Loading
Loading