1
Fork 0

Compare commits

...

4 Commits

Author SHA1 Message Date
Bauke 866d823820
Rework storage values to use a single function. 2023-07-02 12:25:53 +02:00
Bauke 2e0ea98225
Add documentation. 2023-07-02 12:04:29 +02:00
Bauke b130ec37a7
Consolidate all the tour data into a single TourData type. 2023-07-02 11:28:41 +02:00
Bauke 896895c69a
Add the beginnings of the account settings tour.
Also added an error tour for displaying error messages when starting
a tour and a TourRequirements object.
2023-07-01 15:46:23 +02:00
15 changed files with 341 additions and 201 deletions

View File

@ -1,14 +1,17 @@
import Shepherd from "shepherd.js";
import {fromStorage, StorageKey} from "../storage/common.js";
import {
addCompletedTour,
createIntroductionUnderstood,
} from "../storage/common.js";
import {introductionSteps} from "../tours/introduction.js";
import {TourId, tourIdsAndSteps} from "../tours/exports.js";
allTours,
introductionTour,
showTourError,
type TourData,
} from "../tours/exports.js";
/** The main entry point for the content script. */
async function main(): Promise<void> {
const introductionUnderstood = await createIntroductionUnderstood();
const introductionUnderstood = await fromStorage(
StorageKey.IntroductionUnderstood,
);
// Get the anchor without the leading #.
const anchor = window.location.hash.slice(1);
@ -26,9 +29,7 @@ async function main(): Promise<void> {
// If a different tour is selected but the introduction hasn't happened yet,
// then the main function will be rerun once this tour finishes.
startTour(
TourId.Introduction,
introductionSteps,
[],
introductionTour,
startsWithPrefix && anchorTourId !== "introduction",
);
return;
@ -38,11 +39,29 @@ async function main(): Promise<void> {
return;
}
const userIsLoggedIn =
document.querySelector(".logged-in-user-username") !== null;
// Then run through all of the tours we have and start the first match for the
// ID.
for (const [id, steps, eventHandlers] of tourIdsAndSteps) {
if (anchorTourId === id) {
startTour(id, steps, eventHandlers, false);
for (const tour of allTours) {
if (anchorTourId === tour.id) {
if (tour.requirements.mustBeLoggedIn && !userIsLoggedIn) {
showTourError(
`The ${tour.id} tour can only be shown with a logged in account.`,
);
return;
}
if (tour.requirements.path !== window.location.pathname) {
// This tour's path requirement does not match.
showTourError(
`The ${tour.id} tour can only be start on the ${tour.requirements.path} page.`,
);
return;
}
startTour(tour, false);
return;
}
}
@ -58,12 +77,7 @@ async function main(): Promise<void> {
* @param runMainAgainAfterComplete Should the `main` function be run after this
* tour is completed?
*/
function startTour(
tourId: TourId,
steps: TourStepOptions[],
eventHandlers: TourStepEventHandler[],
runMainAgainAfterComplete: boolean,
): void {
function startTour(data: TourData, runMainAgainAfterComplete: boolean): void {
const defaultButtons: Shepherd.Step.StepOptionsButton[] = [
{
classes: "btn",
@ -106,7 +120,9 @@ function startTour(
}
// Mark the tour as completed.
await addCompletedTour(tourId);
const completedTours = await fromStorage(StorageKey.ToursCompleted);
completedTours.value.add(data.id);
await completedTours.save();
if (runMainAgainAfterComplete) {
await main();
@ -115,19 +131,24 @@ function startTour(
// For every step we have, add it to the tour and subsequently add all the
// event handlers to that step.
for (const [stepNumber, stepOptions] of steps.entries()) {
for (const [stepNumber, stepOptions] of data.steps.entries()) {
// If the final step doesn't have buttons defined, set the "Continue" button
// text to "Finish".
if (stepOptions.buttons === undefined && stepNumber + 1 === steps.length) {
if (
stepOptions.buttons === undefined &&
stepNumber + 1 === data.steps.length
) {
stepOptions.buttons = [...defaultButtons];
stepOptions.buttons[0].text = "Finish";
}
const step = tour.addStep(stepOptions);
for (const [targetStepId, [eventName, eventHandler]] of eventHandlers) {
if (targetStepId === step.id) {
step.on(eventName, eventHandler);
for (const {stepId, eventHandlers} of data.eventHandlers) {
if (stepId === step.id) {
for (const {event, handler} of eventHandlers) {
step.on(event, handler);
}
}
}
}

View File

@ -1,59 +1,22 @@
import {Component, type JSX} from "preact";
import {TourId} from "../../tours/exports.js";
import {Component} from "preact";
import {type TourData} from "../../tours/exports.js";
type Props = {
hasBeenCompleted: boolean;
name: string;
tourId: TourId;
tour: TourData;
};
function tourDescription(tourId: Props["tourId"]): JSX.Element {
if (tourId === TourId.Introduction) {
return (
<p class="tour-description">
A short introduction to Tildes Shepherd and how the tours work. Normally
this is automatically shown when you first installed the extension.
</p>
);
}
if (tourId === TourId.InterfaceHomepage) {
return (
<p class="tour-description">
Let's take a look at the home page and all we can do there.
</p>
);
}
return (
<p class="tour-description">
Tour ID "{tourId}" does not have a description, this should probably be
fixed!
</p>
);
}
function tourLink(tourId: Props["tourId"]): string {
const anchor = `#tildes-shepherd-tour=${tourId}`;
function tourLink(tour: TourData): string {
const anchor = `#tildes-shepherd-tour=${tour.id}`;
const baseUrl = "https://tildes.net";
let path = "";
switch (tourId) {
case TourId.InterfaceHomepage:
case TourId.Introduction: {
path = "/";
break;
}
default:
}
const path = tour.requirements.path;
return `${baseUrl}${path}${anchor}`;
}
export class Tour extends Component<Props> {
render() {
const {hasBeenCompleted, name, tourId} = this.props;
const {hasBeenCompleted, tour} = this.props;
const classes = ["tour", hasBeenCompleted ? "completed" : ""].join(" ");
const completed = hasBeenCompleted ? (
<p class="tour-completed" title="You've completed this tour before!">
@ -63,11 +26,11 @@ export class Tour extends Component<Props> {
return (
<div class={classes.trim()}>
<h3>{name}</h3>
<h3>{tour.title}</h3>
{completed}
{tourDescription(tourId)}
{tour.description}
<p class="tour-link">
<a href={tourLink(tourId)}>Take this tour</a>
<a href={tourLink(tour)}>Take this tour</a>
</p>
</div>
);

View File

@ -1,12 +1,16 @@
import {Component, type JSX} from "preact";
import {createToursCompleted} from "../../storage/common.js";
import {TourId} from "../../tours/exports.js";
import {
fromStorage,
StorageKey,
type StorageValues,
} from "../../storage/common.js";
import {allTours} from "../../tours/exports.js";
import {Tour} from "./tour.js";
type Props = Record<string, unknown>;
type State = {
toursCompleted: Awaited<ReturnType<typeof createToursCompleted>>["value"];
toursCompleted: Awaited<StorageValues[StorageKey.ToursCompleted]>;
};
export class Tours extends Component<Props, State> {
@ -14,39 +18,29 @@ export class Tours extends Component<Props, State> {
super(props);
this.state = {
toursCompleted: new Set(),
toursCompleted: undefined!,
};
}
async componentDidMount(): Promise<void> {
const toursCompleted = await createToursCompleted();
this.setState({toursCompleted: toursCompleted.value});
const toursCompleted = await fromStorage(StorageKey.ToursCompleted);
this.setState({toursCompleted});
}
render(): JSX.Element {
const {toursCompleted} = this.state;
if (toursCompleted === undefined) {
return <></>;
}
const createTour = (tourId: TourId, name: string): Tour["props"] => {
return {
hasBeenCompleted: toursCompleted.has(tourId),
name,
tourId,
};
};
const tourProps: Array<Tour["props"]> = [
createTour(TourId.Introduction, "Introduction"),
createTour(TourId.InterfaceHomepage, "The Homepage"),
];
const tours = allTours.map((tour) => (
<Tour hasBeenCompleted={toursCompleted.value.has(tour.id)} tour={tour} />
));
return (
<main>
<h2>Tours</h2>
<div class="tours">
{tourProps.map((props) => (
<Tour {...props} />
))}
</div>
<div class="tours">{tours}</div>
</main>
);
}

View File

@ -2,33 +2,39 @@ import browser from "webextension-polyfill";
import {createValue} from "@holllo/webextension-storage";
import {type TourId} from "../tours/exports.js";
/** All available storage keys. */
export enum StorageKey {
IntroductionUnderstood = "introduction-understood",
ToursCompleted = "tours-completed",
}
export async function createIntroductionUnderstood() {
return createValue<boolean>({
/** All values we want to save in storage. */
const storageValues = {
[StorageKey.IntroductionUnderstood]: createValue<boolean>({
deserialize: (input) => input === "true",
serialize: (input) => JSON.stringify(input),
key: StorageKey.IntroductionUnderstood,
storage: browser.storage.local,
value: false,
});
}
export async function createToursCompleted() {
return createValue<Set<TourId>>({
}),
[StorageKey.ToursCompleted]: createValue<Set<TourId>>({
deserialize: (input) => new Set(JSON.parse(input) as TourId[]),
serialize: (input) => JSON.stringify(Array.from(input)),
key: StorageKey.ToursCompleted,
storage: browser.storage.local,
value: new Set([]),
});
}
}),
};
export async function addCompletedTour(tourId: TourId): Promise<void> {
const toursCompleted = await createToursCompleted();
toursCompleted.value.add(tourId);
await toursCompleted.save();
/** Alias to get the inferred type shape of {@link storageValues}. */
export type StorageValues = typeof storageValues;
/**
* Get the stored value for a given key.
* @param key The key to get from storage.
*/
export async function fromStorage<K extends StorageKey>(
key: K,
): Promise<StorageValues[K]> {
return storageValues[key];
}

View File

@ -1,14 +1,14 @@
import {homepageEventHandlers, homepageSteps} from "./interface/exports.js";
import {introductionSteps} from "./introduction.js";
import {accountSettingsTour, homepageTour} from "./interface/exports.js";
import {introductionTour} from "./introduction.js";
import {type TourData} from "./types.js";
export enum TourId {
InterfaceHomepage = "interface-homepage",
Introduction = "introduction",
}
export * from "./introduction.js";
export * from "./shared/exports.js";
export * from "./types.js";
export const tourIdsAndSteps: Array<
[TourId, TourStepOptions[], TourStepEventHandler[]]
> = [
[TourId.Introduction, introductionSteps, []],
[TourId.InterfaceHomepage, homepageSteps, homepageEventHandlers],
/** All tours available in a single array. */
export const allTours: TourData[] = [
introductionTour,
accountSettingsTour,
homepageTour,
];

View File

@ -0,0 +1,32 @@
import {type TourData, TourId} from "../types.js";
import {renderInContainer} from "../utilities.js";
const step01 = renderInContainer(
<>
<h1>Your Account Settings</h1>
</>,
);
const steps: TourData["steps"] = [
{
id: "account-settings-01",
text: step01,
},
];
const eventHandlers: TourData["eventHandlers"] = [];
const requirements: TourData["requirements"] = {
mustBeLoggedIn: true,
path: "/settings",
};
export const accountSettingsTour: TourData = {
id: TourId.InterfaceAccountSettings,
title: "Your Account Settings",
description: "View your account settings and all that you can customize.",
displayInOptionsPage: true,
eventHandlers,
requirements,
steps,
};

View File

@ -1,4 +1,2 @@
export {
eventHandlers as homepageEventHandlers,
steps as homepageSteps,
} from "./homepage.js";
export * from "./account-settings.js";
export * from "./homepage.js";

View File

@ -1,11 +1,11 @@
import type Shepherd from "shepherd.js";
import {LoggedOutWarning} from "../shared/logged-out-warning.js";
import {type TourData, TourId} from "../types.js";
import {
addDatasetCounter,
encapsulateElements,
removeAllDatasetCounters,
renderInContainer,
} from "../utilities.js";
import {LoggedOutWarning} from "../shared/logged-out-warning.js";
const step01 = renderInContainer(
<>
@ -345,7 +345,7 @@ const step10 = renderInContainer(
</>,
);
export const steps: Shepherd.Step.StepOptions[] = [
const steps: TourData["steps"] = [
{
id: "homepage-01",
text: step01,
@ -433,79 +433,101 @@ export const steps: Shepherd.Step.StepOptions[] = [
},
];
export const eventHandlers: TourStepEventHandler[] = [
[
"homepage-04",
[
"show",
() => {
const topic = ".topic-listing > li:first-child";
const counters = [
".topic-title",
".topic-metadata",
".topic-info-comments",
".topic-info-source",
"time",
".topic-voting",
".topic-actions",
];
const eventHandlers: TourData["eventHandlers"] = [
{
stepId: "homepage-04",
eventHandlers: [
{
event: "show",
handler() {
const topic = ".topic-listing > li:first-child";
const counters = [
".topic-title",
".topic-metadata",
".topic-info-comments",
".topic-info-source",
"time",
".topic-voting",
".topic-actions",
];
for (const [count, selector] of counters.entries()) {
addDatasetCounter(`${topic} ${selector}`, count + 1);
}
for (const [count, selector] of counters.entries()) {
addDatasetCounter(`${topic} ${selector}`, count + 1);
}
},
},
],
],
[
"homepage-05",
[
"destroy",
() => {
removeAllDatasetCounters();
},
{
stepId: "homepage-05",
eventHandlers: [
{
event: "destroy",
handler() {
removeAllDatasetCounters();
},
},
{
event: "show",
handler() {
encapsulateElements(
"homepage-06",
"#sidebar .sidebar-controls",
"afterend",
["#sidebar .form-search", "#sidebar h2", "#sidebar p"],
);
},
},
],
],
[
"homepage-05",
[
"show",
() => {
encapsulateElements(
"homepage-06",
"#sidebar .sidebar-controls",
"afterend",
["#sidebar .form-search", "#sidebar h2", "#sidebar p"],
);
},
{
stepId: "homepage-06",
eventHandlers: [
{
event: "show",
handler() {
encapsulateElements(
"homepage-07",
"#sidebar .divider",
"beforebegin",
["#sidebar .nav", '#sidebar [href="/groups"'],
);
},
},
],
],
[
"homepage-06",
[
"show",
() => {
encapsulateElements("homepage-07", "#sidebar .divider", "beforebegin", [
"#sidebar .nav",
'#sidebar [href="/groups"',
]);
},
],
],
[
"homepage-08",
[
"show",
() => {
const filteredTags =
document.querySelector<HTMLDetailsElement>("#sidebar details") ??
undefined;
if (filteredTags === undefined) {
console.warn("Element is unexpectedly undefined");
return;
}
},
{
stepId: "homepage-08",
eventHandlers: [
{
event: "show",
handler() {
const filteredTags =
document.querySelector<HTMLDetailsElement>("#sidebar details") ??
undefined;
if (filteredTags === undefined) {
console.warn("Element is unexpectedly undefined");
return;
}
filteredTags.open = true;
filteredTags.open = true;
},
},
],
],
},
];
const requirements: TourData["requirements"] = {
mustBeLoggedIn: false,
path: "/",
};
export const homepageTour: TourData = {
id: TourId.InterfaceHomepage,
title: "The Tildes Homepage",
description: "Let's take a look at the home page and all we can do there.",
displayInOptionsPage: true,
eventHandlers,
requirements,
steps,
};

View File

@ -1,5 +1,5 @@
import type Shepherd from "shepherd.js";
import {createIntroductionUnderstood} from "../storage/common.js";
import {fromStorage, StorageKey} from "../storage/common.js";
import {TourId, type TourData} from "./types.js";
import {openOptionsPageFromBackground, renderInContainer} from "./utilities.js";
const step01 = renderInContainer(
@ -82,7 +82,7 @@ const step03 = renderInContainer(
</>,
);
export const introductionSteps: Shepherd.Step.StepOptions[] = [
const steps: TourData["steps"] = [
{
canClickTarget: false,
id: "introduction-01",
@ -103,7 +103,9 @@ export const introductionSteps: Shepherd.Step.StepOptions[] = [
classes: "btn",
text: "I understand",
async action() {
const introductionUnderstood = await createIntroductionUnderstood();
const introductionUnderstood = await fromStorage(
StorageKey.IntroductionUnderstood,
);
introductionUnderstood.value = true;
await introductionUnderstood.save();
this.complete();
@ -122,3 +124,21 @@ export const introductionSteps: Shepherd.Step.StepOptions[] = [
text: step03,
},
];
const eventHandlers: TourData["eventHandlers"] = [];
const requirements: TourData["requirements"] = {
mustBeLoggedIn: false,
path: "/",
};
export const introductionTour: TourData = {
id: TourId.Introduction,
title: "Tildes Shepherd Introduction",
description:
"A short introduction to Tildes Shepherd and how the tours work.",
displayInOptionsPage: true,
eventHandlers,
requirements,
steps,
};

View File

@ -1 +1,2 @@
export * from "./logged-out-warning.js";
export * from "./tour-error.js";

View File

@ -1,5 +1,6 @@
import {type JSX} from "preact";
/** Check if the user is logged in and return a warning element if they aren't. */
export function LoggedOutWarning(): JSX.Element {
const userIsLoggedIn =
document.querySelector(".logged-in-user-username") !== null;

View File

@ -0,0 +1,29 @@
import Shepherd from "shepherd.js";
import {renderInContainer} from "../utilities.js";
/**
* Start an ad-hoc tour to display an error message.
* @param text The message to show.
*/
export function showTourError(text: string) {
const tour = new Shepherd.Tour({
defaultStepOptions: {
buttons: [
{
classes: "btn",
text: "Continue",
action() {
this.complete();
},
},
],
},
useModalOverlay: true,
});
tour.addStep({
text: renderInContainer(<p class="tish-warning">{text}</p>),
});
tour.start();
}

58
source/tours/types.ts Normal file
View File

@ -0,0 +1,58 @@
import type Shepherd from "shepherd.js";
/** All available tour IDs. */
export enum TourId {
InterfaceAccountSettings = "interface-account-settings",
InterfaceHomepage = "interface-homepage",
Introduction = "introduction",
}
/** Requirements of a tour to be checked before the tour is started. */
export type TourRequirement = {
/**
* This tour requires that the user must be logged in. Only set this to true
* if the tour goes to pages only accessible by logged in users.
*/
mustBeLoggedIn: boolean;
/** The {@link URL.pathname} to run the tour at. */
path: string;
};
/** An individual tour step event handler. */
export type TourStepEvent = {
/**
* - The "show" event will be called when the step is displayed.
* - The "destroy" event will be called when the step is finished.
*/
event: "show" | "destroy";
/** The handler for this step event. */
handler: Parameters<Shepherd.Step["on"]>[1];
};
/** All the tour data collected in one place. */
export type TourData = {
/** A short description of the tour for use in the options page. */
description: string;
/** Whether this tour should be shown in the options page. */
displayInOptionsPage: boolean;
/** All event handlers to be added to this tour's steps. */
eventHandlers: Array<{
eventHandlers: TourStepEvent[];
stepId: string;
}>;
/** The unique ID for this tour. */
id: TourId;
/** The requirements this tour must match before starting it. */
requirements: TourRequirement;
/** All the steps this tour will take. */
steps: Shepherd.Step.StepOptions[];
/** The title of the tour for use in the options page. */
title: string;
};

View File

@ -5,7 +5,7 @@ import browser from "webextension-polyfill";
* Adds a `[data-tildes-shepherd-counter]` attribute to a specified element. For
* the associated CSS, see `source/content-scripts/scss/main.scss`.
*
* @param selector The selector of element to apply the counter to, if the
* @param selector The selector of the element to apply the counter to, if the
* target element can't be selected an error will be thrown.
* @param count The number to display in the counter.
*/

7
source/types.d.ts vendored
View File

@ -1,12 +1,7 @@
import type Shepherd from "shepherd.js";
export {};
declare global {
const $browser: "chromium" | "firefox";
const $dev: boolean;
const $test: boolean;
type TourStepEvent = "show" | "destroy";
type TourStepEventFunction = Parameters<Shepherd.Step["on"]>[1];
type TourStepEventHandler = [string, [TourStepEvent, TourStepEventFunction]];
type TourStepOptions = Shepherd.Step.StepOptions;
}