Refactoring: port reviews to svelte
This commit is contained in:
parent
6edcd7d73c
commit
6d5f5d54f8
41 changed files with 683 additions and 462 deletions
|
@ -1,34 +1,35 @@
|
|||
import { ImmutableStore, Store, UIEventSource } from "../UIEventSource"
|
||||
import { MangroveReviews, Review } from "mangrove-reviews-typescript"
|
||||
import { Utils } from "../../Utils"
|
||||
import { Feature, Position } from "geojson"
|
||||
import { GeoOperations } from "../GeoOperations"
|
||||
import { ImmutableStore, Store, UIEventSource } from "../UIEventSource";
|
||||
import { MangroveReviews, Review } from "mangrove-reviews-typescript";
|
||||
import { Utils } from "../../Utils";
|
||||
import { Feature, Position } from "geojson";
|
||||
import { GeoOperations } from "../GeoOperations";
|
||||
|
||||
export class MangroveIdentity {
|
||||
public readonly keypair: Store<CryptoKeyPair>
|
||||
public readonly key_id: Store<string>
|
||||
public readonly keypair: Store<CryptoKeyPair>;
|
||||
public readonly key_id: Store<string>;
|
||||
|
||||
constructor(mangroveIdentity: UIEventSource<string>) {
|
||||
const key_id = new UIEventSource<string>(undefined)
|
||||
this.key_id = key_id
|
||||
const keypairEventSource = new UIEventSource<CryptoKeyPair>(undefined)
|
||||
this.keypair = keypairEventSource
|
||||
const key_id = new UIEventSource<string>(undefined);
|
||||
this.key_id = key_id;
|
||||
const keypairEventSource = new UIEventSource<CryptoKeyPair>(undefined);
|
||||
this.keypair = keypairEventSource;
|
||||
mangroveIdentity.addCallbackAndRunD(async (data) => {
|
||||
if (data === "") {
|
||||
return
|
||||
return;
|
||||
}
|
||||
const keypair = await MangroveReviews.jwkToKeypair(JSON.parse(data))
|
||||
keypairEventSource.setData(keypair)
|
||||
const pem = await MangroveReviews.publicToPem(keypair.publicKey)
|
||||
key_id.setData(pem)
|
||||
})
|
||||
const keypair = await MangroveReviews.jwkToKeypair(JSON.parse(data));
|
||||
keypairEventSource.setData(keypair);
|
||||
const pem = await MangroveReviews.publicToPem(keypair.publicKey);
|
||||
key_id.setData(pem);
|
||||
});
|
||||
|
||||
try {
|
||||
if (!Utils.runningFromConsole && (mangroveIdentity.data ?? "") === "") {
|
||||
MangroveIdentity.CreateIdentity(mangroveIdentity).then((_) => {})
|
||||
MangroveIdentity.CreateIdentity(mangroveIdentity).then((_) => {
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Could not create identity: ", e)
|
||||
console.error("Could not create identity: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -38,13 +39,13 @@ export class MangroveIdentity {
|
|||
* @constructor
|
||||
*/
|
||||
private static async CreateIdentity(identity: UIEventSource<string>): Promise<void> {
|
||||
const keypair = await MangroveReviews.generateKeypair()
|
||||
const jwk = await MangroveReviews.keypairToJwk(keypair)
|
||||
const keypair = await MangroveReviews.generateKeypair();
|
||||
const jwk = await MangroveReviews.keypairToJwk(keypair);
|
||||
if ((identity.data ?? "") !== "") {
|
||||
// Identity has been loaded via osmPreferences by now - we don't overwrite
|
||||
return
|
||||
return;
|
||||
}
|
||||
identity.setData(JSON.stringify(jwk))
|
||||
identity.setData(JSON.stringify(jwk));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -52,17 +53,18 @@ export class MangroveIdentity {
|
|||
* Tracks all reviews of a given feature, allows to create a new review
|
||||
*/
|
||||
export default class FeatureReviews {
|
||||
private static readonly _featureReviewsCache: Record<string, FeatureReviews> = {}
|
||||
public readonly subjectUri: Store<string>
|
||||
private static readonly _featureReviewsCache: Record<string, FeatureReviews> = {};
|
||||
public readonly subjectUri: Store<string>;
|
||||
public readonly average: Store<number | null>;
|
||||
private readonly _reviews: UIEventSource<(Review & { madeByLoggedInUser: Store<boolean> })[]> =
|
||||
new UIEventSource([])
|
||||
new UIEventSource([]);
|
||||
public readonly reviews: Store<(Review & { madeByLoggedInUser: Store<boolean> })[]> =
|
||||
this._reviews
|
||||
private readonly _lat: number
|
||||
private readonly _lon: number
|
||||
private readonly _uncertainty: number
|
||||
private readonly _name: Store<string>
|
||||
private readonly _identity: MangroveIdentity
|
||||
this._reviews;
|
||||
private readonly _lat: number;
|
||||
private readonly _lon: number;
|
||||
private readonly _uncertainty: number;
|
||||
private readonly _name: Store<string>;
|
||||
private readonly _identity: MangroveIdentity;
|
||||
|
||||
private constructor(
|
||||
feature: Feature,
|
||||
|
@ -75,55 +77,72 @@ export default class FeatureReviews {
|
|||
}
|
||||
) {
|
||||
const centerLonLat = GeoOperations.centerpointCoordinates(feature)
|
||||
;[this._lon, this._lat] = centerLonLat
|
||||
;[this._lon, this._lat] = centerLonLat;
|
||||
this._identity =
|
||||
mangroveIdentity ?? new MangroveIdentity(new UIEventSource<string>(undefined))
|
||||
const nameKey = options?.nameKey ?? "name"
|
||||
mangroveIdentity ?? new MangroveIdentity(new UIEventSource<string>(undefined));
|
||||
const nameKey = options?.nameKey ?? "name";
|
||||
|
||||
if (feature.geometry.type === "Point") {
|
||||
this._uncertainty = options?.uncertaintyRadius ?? 10
|
||||
this._uncertainty = options?.uncertaintyRadius ?? 10;
|
||||
} else {
|
||||
let coordss: Position[][]
|
||||
let coordss: Position[][];
|
||||
if (feature.geometry.type === "LineString") {
|
||||
coordss = [feature.geometry.coordinates]
|
||||
coordss = [feature.geometry.coordinates];
|
||||
} else if (
|
||||
feature.geometry.type === "MultiLineString" ||
|
||||
feature.geometry.type === "Polygon"
|
||||
) {
|
||||
coordss = feature.geometry.coordinates
|
||||
coordss = feature.geometry.coordinates;
|
||||
}
|
||||
let maxDistance = 0
|
||||
let maxDistance = 0;
|
||||
for (const coords of coordss) {
|
||||
for (const coord of coords) {
|
||||
maxDistance = Math.max(
|
||||
maxDistance,
|
||||
GeoOperations.distanceBetween(centerLonLat, coord)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this._uncertainty = options?.uncertaintyRadius ?? maxDistance
|
||||
this._uncertainty = options?.uncertaintyRadius ?? maxDistance;
|
||||
}
|
||||
this._name = tagsSource.map((tags) => tags[nameKey] ?? options?.fallbackName)
|
||||
this._name = tagsSource.map((tags) => tags[nameKey] ?? options?.fallbackName);
|
||||
|
||||
this.subjectUri = this.ConstructSubjectUri()
|
||||
this.subjectUri = this.ConstructSubjectUri();
|
||||
|
||||
const self = this
|
||||
const self = this;
|
||||
this.subjectUri.addCallbackAndRunD(async (sub) => {
|
||||
const reviews = await MangroveReviews.getReviews({ sub })
|
||||
self.addReviews(reviews.reviews)
|
||||
})
|
||||
const reviews = await MangroveReviews.getReviews({ sub });
|
||||
self.addReviews(reviews.reviews);
|
||||
});
|
||||
/* We also construct all subject queries _without_ encoding the name to work around a previous bug
|
||||
* See https://github.com/giggls/opencampsitemap/issues/30
|
||||
*/
|
||||
this.ConstructSubjectUri(true).addCallbackAndRunD(async (sub) => {
|
||||
try {
|
||||
const reviews = await MangroveReviews.getReviews({ sub })
|
||||
self.addReviews(reviews.reviews)
|
||||
const reviews = await MangroveReviews.getReviews({ sub });
|
||||
self.addReviews(reviews.reviews);
|
||||
} catch (e) {
|
||||
console.log("Could not fetch reviews for partially incorrect query ", sub)
|
||||
console.log("Could not fetch reviews for partially incorrect query ", sub);
|
||||
}
|
||||
})
|
||||
});
|
||||
this.average = this._reviews.map(reviews => {
|
||||
if (!reviews) {
|
||||
return null;
|
||||
}
|
||||
if(reviews.length === 0){
|
||||
return null
|
||||
}
|
||||
let sum = 0;
|
||||
let count = 0;
|
||||
for (const review of reviews) {
|
||||
if (review.rating !== undefined) {
|
||||
count++;
|
||||
sum += review.rating;
|
||||
}
|
||||
}
|
||||
return Math.round(sum / count)
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -139,14 +158,14 @@ export default class FeatureReviews {
|
|||
uncertaintyRadius?: number
|
||||
}
|
||||
) {
|
||||
const key = feature.properties.id
|
||||
const cached = FeatureReviews._featureReviewsCache[key]
|
||||
const key = feature.properties.id;
|
||||
const cached = FeatureReviews._featureReviewsCache[key];
|
||||
if (cached !== undefined) {
|
||||
return cached
|
||||
return cached;
|
||||
}
|
||||
const featureReviews = new FeatureReviews(feature, tagsSource, mangroveIdentity, options)
|
||||
FeatureReviews._featureReviewsCache[key] = featureReviews
|
||||
return featureReviews
|
||||
const featureReviews = new FeatureReviews(feature, tagsSource, mangroveIdentity, options);
|
||||
FeatureReviews._featureReviewsCache[key] = featureReviews;
|
||||
return featureReviews;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -155,15 +174,15 @@ export default class FeatureReviews {
|
|||
public async createReview(review: Omit<Review, "sub">): Promise<void> {
|
||||
const r: Review = {
|
||||
sub: this.subjectUri.data,
|
||||
...review,
|
||||
}
|
||||
const keypair: CryptoKeyPair = this._identity.keypair.data
|
||||
console.log(r)
|
||||
const jwt = await MangroveReviews.signReview(keypair, r)
|
||||
console.log("Signed:", jwt)
|
||||
await MangroveReviews.submitReview(jwt)
|
||||
this._reviews.data.push({ ...r, madeByLoggedInUser: new ImmutableStore(true) })
|
||||
this._reviews.ping()
|
||||
...review
|
||||
};
|
||||
const keypair: CryptoKeyPair = this._identity.keypair.data;
|
||||
console.log(r);
|
||||
const jwt = await MangroveReviews.signReview(keypair, r);
|
||||
console.log("Signed:", jwt);
|
||||
await MangroveReviews.submitReview(jwt);
|
||||
this._reviews.data.push({ ...r, madeByLoggedInUser: new ImmutableStore(true) });
|
||||
this._reviews.ping();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -172,46 +191,48 @@ export default class FeatureReviews {
|
|||
* @private
|
||||
*/
|
||||
private addReviews(reviews: { payload: Review; kid: string }[]) {
|
||||
const self = this
|
||||
const alreadyKnown = new Set(self._reviews.data.map((r) => r.rating + " " + r.opinion))
|
||||
const self = this;
|
||||
const alreadyKnown = new Set(self._reviews.data.map((r) => r.rating + " " + r.opinion));
|
||||
|
||||
let hasNew = false
|
||||
let hasNew = false;
|
||||
for (const reviewData of reviews) {
|
||||
const review = reviewData.payload
|
||||
const review = reviewData.payload;
|
||||
|
||||
try {
|
||||
const url = new URL(review.sub)
|
||||
console.log("URL is", url)
|
||||
const url = new URL(review.sub);
|
||||
console.log("URL is", url);
|
||||
if (url.protocol === "geo:") {
|
||||
const coordinate = <[number, number]>(
|
||||
url.pathname.split(",").map((n) => Number(n))
|
||||
)
|
||||
);
|
||||
const distance = GeoOperations.distanceBetween(
|
||||
[this._lat, this._lon],
|
||||
coordinate
|
||||
)
|
||||
);
|
||||
if (distance > this._uncertainty) {
|
||||
continue
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(e)
|
||||
console.warn(e);
|
||||
}
|
||||
|
||||
const key = review.rating + " " + review.opinion
|
||||
const key = review.rating + " " + review.opinion;
|
||||
if (alreadyKnown.has(key)) {
|
||||
continue
|
||||
continue;
|
||||
}
|
||||
self._reviews.data.push({
|
||||
...review,
|
||||
madeByLoggedInUser: this._identity.key_id.map((user_key_id) => {
|
||||
return reviewData.kid === user_key_id
|
||||
}),
|
||||
})
|
||||
hasNew = true
|
||||
return reviewData.kid === user_key_id;
|
||||
})
|
||||
});
|
||||
hasNew = true;
|
||||
}
|
||||
if (hasNew) {
|
||||
self._reviews.ping()
|
||||
self._reviews.data.sort((a, b) => b.iat - a.iat) // Sort with most recent first
|
||||
|
||||
self._reviews.ping();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -224,13 +245,13 @@ export default class FeatureReviews {
|
|||
private ConstructSubjectUri(dontEncodeName: boolean = false): Store<string> {
|
||||
// https://www.rfc-editor.org/rfc/rfc5870#section-3.4.2
|
||||
// `u` stands for `uncertainty`, https://www.rfc-editor.org/rfc/rfc5870#section-3.4.3
|
||||
const self = this
|
||||
return this._name.map(function (name) {
|
||||
let uri = `geo:${self._lat},${self._lon}?u=${self._uncertainty}`
|
||||
const self = this;
|
||||
return this._name.map(function(name) {
|
||||
let uri = `geo:${self._lat},${self._lon}?u=${self._uncertainty}`;
|
||||
if (name) {
|
||||
uri += "&q=" + (dontEncodeName ? name : encodeURIComponent(name))
|
||||
uri += "&q=" + (dontEncodeName ? name : encodeURIComponent(name));
|
||||
}
|
||||
return uri
|
||||
})
|
||||
return uri;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -46,7 +46,7 @@
|
|||
>
|
||||
{#each layer.titleIcons as titleIconConfig}
|
||||
{#if (titleIconConfig.condition?.matchesProperties(_tags) ?? true) && (titleIconConfig.metacondition?.matchesProperties( { ..._metatags, ..._tags } ) ?? true) && titleIconConfig.IsKnown(_tags)}
|
||||
<div class="flex h-8 w-8 items-center">
|
||||
<div class={titleIconConfig.renderIconClass ?? "flex h-8 w-8 items-center"}>
|
||||
<TagRenderingAnswer
|
||||
config={titleIconConfig}
|
||||
{tags}
|
||||
|
|
47
src/UI/Reviews/AllReviews.svelte
Normal file
47
src/UI/Reviews/AllReviews.svelte
Normal file
|
@ -0,0 +1,47 @@
|
|||
<script lang="ts">
|
||||
import FeatureReviews from "../../Logic/Web/MangroveReviews";
|
||||
import SingleReview from "./SingleReview.svelte";
|
||||
import { Utils } from "../../Utils";
|
||||
import StarsBar from "./StarsBar.svelte";
|
||||
import ReviewForm from "./ReviewForm.svelte";
|
||||
import Translations from "../i18n/Translations";
|
||||
import Tr from "../Base/Tr.svelte";
|
||||
import type { SpecialVisualizationState } from "../SpecialVisualization";
|
||||
import { UIEventSource } from "../../Logic/UIEventSource";
|
||||
import type { Feature } from "geojson";
|
||||
import LayerConfig from "../../Models/ThemeConfig/LayerConfig";
|
||||
import ToSvelte from "../Base/ToSvelte.svelte";
|
||||
import Svg from "../../Svg";
|
||||
|
||||
/**
|
||||
* An element showing all reviews
|
||||
*/
|
||||
export let reviews: FeatureReviews;
|
||||
export let state: SpecialVisualizationState;
|
||||
export let tags: UIEventSource<Record<string, string>>;
|
||||
export let feature: Feature;
|
||||
export let layer: LayerConfig;
|
||||
let average = reviews.average;
|
||||
let _reviews = [];
|
||||
reviews.reviews.addCallbackAndRunD(r => {
|
||||
_reviews = Utils.NoNull(r);
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
<div class="border-gray-300 border-dashed border-2">
|
||||
{#if _reviews.length > 1}
|
||||
<StarsBar score={$average}></StarsBar>
|
||||
{/if}
|
||||
{#if _reviews.length > 0}
|
||||
{#each _reviews as review}
|
||||
<SingleReview {review}></SingleReview>
|
||||
{/each}
|
||||
{:else}
|
||||
<Tr t={Translations.t.reviews.no_reviews_yet} />
|
||||
{/if}
|
||||
<div class="flex justify-end">
|
||||
<ToSvelte construct={Svg.mangrove_logo_svg().SetClass("w-12 h-12")} />
|
||||
<Tr t={Translations.t.reviews.attribution} />
|
||||
</div>
|
||||
</div>
|
|
@ -1,56 +0,0 @@
|
|||
import Combine from "../Base/Combine"
|
||||
import Translations from "../i18n/Translations"
|
||||
import SingleReview from "./SingleReview"
|
||||
import BaseUIElement from "../BaseUIElement"
|
||||
import Img from "../Base/Img"
|
||||
import { VariableUiElement } from "../Base/VariableUIElement"
|
||||
import Link from "../Base/Link"
|
||||
import FeatureReviews from "../../Logic/Web/MangroveReviews"
|
||||
|
||||
/**
|
||||
* Shows the reviews and scoring base on mangrove.reviews
|
||||
* The middle element is some other component shown in the middle, e.g. the review input element
|
||||
*/
|
||||
export default class ReviewElement extends VariableUiElement {
|
||||
constructor(reviews: FeatureReviews, middleElement: BaseUIElement) {
|
||||
super(
|
||||
reviews.reviews.map(
|
||||
(revs) => {
|
||||
const elements = []
|
||||
revs.sort((a, b) => b.iat - a.iat) // Sort with most recent first
|
||||
const avg =
|
||||
revs.map((review) => review.rating).reduce((a, b) => a + b, 0) / revs.length
|
||||
elements.push(
|
||||
new Combine([
|
||||
SingleReview.GenStars(avg),
|
||||
new Link(
|
||||
revs.length === 1
|
||||
? Translations.t.reviews.title_singular.Clone()
|
||||
: Translations.t.reviews.title.Subs({
|
||||
count: "" + revs.length,
|
||||
}),
|
||||
`https://mangrove.reviews/search?sub=${encodeURIComponent(
|
||||
reviews.subjectUri.data
|
||||
)}`,
|
||||
true
|
||||
),
|
||||
]).SetClass("font-2xl flex justify-between items-center pl-2 pr-2")
|
||||
)
|
||||
|
||||
elements.push(middleElement)
|
||||
|
||||
elements.push(...revs.map((review) => new SingleReview(review)))
|
||||
elements.push(
|
||||
new Combine([
|
||||
Translations.t.reviews.attribution.Clone(),
|
||||
new Img("./assets/mangrove_logo.png"),
|
||||
]).SetClass("review-attribution")
|
||||
)
|
||||
|
||||
return new Combine(elements).SetClass("block")
|
||||
},
|
||||
[reviews.subjectUri]
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
97
src/UI/Reviews/ReviewForm.svelte
Normal file
97
src/UI/Reviews/ReviewForm.svelte
Normal file
|
@ -0,0 +1,97 @@
|
|||
<script lang="ts">
|
||||
import FeatureReviews from "../../Logic/Web/MangroveReviews";
|
||||
import StarsBar from "./StarsBar.svelte";
|
||||
import SpecialTranslation from "../Popup/TagRendering/SpecialTranslation.svelte";
|
||||
import type { SpecialVisualizationState } from "../SpecialVisualization";
|
||||
import { UIEventSource } from "../../Logic/UIEventSource";
|
||||
import type { Feature } from "geojson";
|
||||
import LayerConfig from "../../Models/ThemeConfig/LayerConfig";
|
||||
import Translations from "../i18n/Translations";
|
||||
import Checkbox from "../Base/Checkbox.svelte";
|
||||
import Tr from "../Base/Tr.svelte";
|
||||
import If from "../Base/If.svelte";
|
||||
import Loading from "../Base/Loading.svelte";
|
||||
import { Review } from "mangrove-reviews-typescript";
|
||||
import { Utils } from "../../Utils";
|
||||
|
||||
export let state: SpecialVisualizationState;
|
||||
export let tags: UIEventSource<Record<string, string>>;
|
||||
export let feature: Feature;
|
||||
export let layer: LayerConfig;
|
||||
/**
|
||||
* The form to create a new review.
|
||||
* This is multi-stepped.
|
||||
*/
|
||||
export let reviews: FeatureReviews;
|
||||
|
||||
let score = 0;
|
||||
let confirmedScore = undefined;
|
||||
let isAffiliated = new UIEventSource(false);
|
||||
let opinion = new UIEventSource<string>(undefined);
|
||||
|
||||
const t = Translations.t.reviews;
|
||||
|
||||
let _state: "ask" | "saving" | "done" = "ask";
|
||||
|
||||
const connection = state.osmConnection;
|
||||
|
||||
async function save() {
|
||||
_state = "saving";
|
||||
let nickname = undefined;
|
||||
if (connection.isLoggedIn.data) {
|
||||
nickname = connection.userDetails.data.name;
|
||||
}
|
||||
const review: Omit<Review, "sub"> = {
|
||||
rating: confirmedScore,
|
||||
opinion: opinion.data,
|
||||
metadata: { nickname, is_affiliated: isAffiliated.data }
|
||||
};
|
||||
if (state.featureSwitchIsTesting.data) {
|
||||
console.log("Testing - not actually saving review", review);
|
||||
await Utils.waitFor(1000);
|
||||
} else {
|
||||
await reviews.createReview(review);
|
||||
}
|
||||
_state = "done";
|
||||
}
|
||||
</script>
|
||||
{#if _state === "done"}
|
||||
<Tr cls="thanks w-full" t={t.saved} />
|
||||
{:else if _state === "saving"}
|
||||
<Loading>
|
||||
<Tr t={t.saving_review} />
|
||||
</Loading>
|
||||
{:else}
|
||||
<div class="interactive border-interactive p-1">
|
||||
<div class="font-bold">
|
||||
<SpecialTranslation {feature} {layer} {state} t={Translations.t.reviews.question} {tags}></SpecialTranslation>
|
||||
</div>
|
||||
<StarsBar on:click={e => {confirmedScore = e.detail.score}} on:hover={e => {score = e.detail.score}}
|
||||
on:mouseout={e => {score = null}} score={score ?? confirmedScore ?? 0}
|
||||
starSize="w-8 h-8"></StarsBar>
|
||||
|
||||
{#if confirmedScore !== undefined}
|
||||
<Tr cls="font-bold mt-2" t={t.question_opinion} />
|
||||
<textarea bind:value={$opinion} inputmode="text" rows="3" class="w-full mb-1" />
|
||||
<Checkbox selected={isAffiliated}>
|
||||
<div class="flex flex-col">
|
||||
<Tr t={t.i_am_affiliated} />
|
||||
<Tr cls="subtle" t={t.i_am_affiliated_explanation} />
|
||||
</div>
|
||||
</Checkbox>
|
||||
<div class="flex w-full justify-between flex-wrap items-center">
|
||||
<If condition={state.osmConnection.isLoggedIn}>
|
||||
<Tr t={t.reviewing_as.Subs({nickname: state.osmConnection.userDetails.data.name})} />
|
||||
<Tr slot="else" t={t.reviewing_as_anonymous} />
|
||||
</If>
|
||||
<button class="primary" on:click={save}>
|
||||
<Tr t={t.save} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<Tr cls="subtle mt-4" t={t.tos} />
|
||||
|
||||
{/if}
|
||||
|
||||
</div>
|
||||
{/if}
|
|
@ -1,101 +0,0 @@
|
|||
import { Review } from "mangrove-reviews-typescript"
|
||||
import { Store, UIEventSource } from "../../Logic/UIEventSource"
|
||||
import { TextField } from "../Input/TextField"
|
||||
import Translations from "../i18n/Translations"
|
||||
import Combine from "../Base/Combine"
|
||||
import Svg from "../../Svg"
|
||||
import { VariableUiElement } from "../Base/VariableUIElement"
|
||||
import { CheckBox } from "../Input/Checkboxes"
|
||||
import UserDetails, { OsmConnection } from "../../Logic/Osm/OsmConnection"
|
||||
import Toggle from "../Input/Toggle"
|
||||
import { LoginToggle } from "../Popup/LoginButton"
|
||||
import { SubtleButton } from "../Base/SubtleButton"
|
||||
|
||||
export default class ReviewForm extends LoginToggle {
|
||||
constructor(
|
||||
onSave: (r: Omit<Review, "sub">) => Promise<void>,
|
||||
state: {
|
||||
readonly osmConnection: OsmConnection
|
||||
readonly featureSwitchUserbadge: Store<boolean>
|
||||
}
|
||||
) {
|
||||
/* made_by_user: new UIEventSource<boolean>(true),
|
||||
rating: undefined,
|
||||
comment: undefined,
|
||||
author: osmConnection.userDetails.data.name,
|
||||
affiliated: false,
|
||||
date: new Date(),*/
|
||||
const commentForm = new TextField({
|
||||
placeholder: Translations.t.reviews.write_a_comment.Clone(),
|
||||
htmlType: "area",
|
||||
textAreaRows: 5,
|
||||
})
|
||||
|
||||
const rating = new UIEventSource<number>(undefined)
|
||||
const isAffiliated = new CheckBox(Translations.t.reviews.i_am_affiliated)
|
||||
const reviewMade = new UIEventSource(false)
|
||||
|
||||
const postingAs = new Combine([
|
||||
Translations.t.reviews.posting_as.Clone(),
|
||||
new VariableUiElement(
|
||||
state.osmConnection.userDetails.map((ud: UserDetails) => ud.name)
|
||||
).SetClass("review-author"),
|
||||
]).SetStyle("display:flex;flex-direction: column;align-items: flex-end;margin-left: auto;")
|
||||
|
||||
const saveButton = new Toggle(
|
||||
Translations.t.reviews.no_rating.SetClass("block alert"),
|
||||
new SubtleButton(Svg.confirm_svg(), Translations.t.reviews.save)
|
||||
.OnClickWithLoading(
|
||||
Translations.t.reviews.saving_review.SetClass("alert"),
|
||||
async () => {
|
||||
const review: Omit<Review, "sub"> = {
|
||||
rating: rating.data,
|
||||
opinion: commentForm.GetValue().data,
|
||||
metadata: { nickname: state.osmConnection.userDetails.data.name },
|
||||
}
|
||||
await onSave(review)
|
||||
}
|
||||
)
|
||||
.SetClass("break-normal"),
|
||||
rating.map((r) => r === undefined, [commentForm.GetValue()])
|
||||
)
|
||||
|
||||
const stars = []
|
||||
for (let i = 1; i <= 5; i++) {
|
||||
stars.push(
|
||||
new VariableUiElement(
|
||||
rating.map((score) => {
|
||||
if (score === undefined) {
|
||||
return Svg.star_outline.replace(/#000000/g, "#ccc")
|
||||
}
|
||||
return score < i * 20 ? Svg.star_outline : Svg.star
|
||||
})
|
||||
).onClick(() => {
|
||||
rating.setData(i * 20)
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
const form = new Combine([
|
||||
new Combine([new Combine(stars).SetClass("review-form-rating"), postingAs]).SetClass(
|
||||
"flex"
|
||||
),
|
||||
commentForm,
|
||||
new Combine([isAffiliated, saveButton]),
|
||||
Translations.t.reviews.tos.Clone().SetClass("subtle"),
|
||||
])
|
||||
.SetClass("flex flex-col p-4")
|
||||
.SetStyle(
|
||||
"border-radius: 1em;" +
|
||||
" background-color: var(--subtle-detail-color);" +
|
||||
" color: var(--subtle-detail-color-contrast);" +
|
||||
" border: 2px solid var(--subtle-detail-color-contrast)"
|
||||
)
|
||||
|
||||
super(
|
||||
new Toggle(Translations.t.reviews.saved.Clone().SetClass("thanks"), form, reviewMade),
|
||||
Translations.t.reviews.plz_login,
|
||||
state
|
||||
)
|
||||
}
|
||||
}
|
38
src/UI/Reviews/SingleReview.svelte
Normal file
38
src/UI/Reviews/SingleReview.svelte
Normal file
|
@ -0,0 +1,38 @@
|
|||
<script lang="ts">
|
||||
import { Review } from "mangrove-reviews-typescript";
|
||||
import { Store } from "../../Logic/UIEventSource";
|
||||
import StarsBar from "./StarsBar.svelte";
|
||||
import Translations from "../i18n/Translations";
|
||||
import Tr from "../Base/Tr.svelte";
|
||||
|
||||
export let review: Review & { madeByLoggedInUser: Store<boolean> };
|
||||
let name = review.metadata.nickname;
|
||||
name ??= (review.metadata.given_name ?? "") + " " + (review.metadata.family_name ?? "").trim();
|
||||
if (name.length === 0) {
|
||||
name = "Anonymous";
|
||||
}
|
||||
let d = new Date();
|
||||
d.setTime(review.iat * 1000);
|
||||
let date = d.toDateString();
|
||||
let byLoggedInUser = review.madeByLoggedInUser;
|
||||
</script>
|
||||
|
||||
<div class={"low-interaction p-1 px-2 rounded-lg "+ ($byLoggedInUser ? "border-interactive" : "")}>
|
||||
<div class="flex justify-between items-center">
|
||||
<StarsBar score={review.rating}></StarsBar>
|
||||
<div class="flex flex-wrap space-x-2">
|
||||
<div class="font-bold">
|
||||
{name}
|
||||
</div>
|
||||
<span class="subtle">
|
||||
{date}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{#if review.opinion}
|
||||
{review.opinion}
|
||||
{/if}
|
||||
{#if review.metadata.is_affiliated}
|
||||
<Tr t={Translations.t.reviews.affiliated_reviewer_warning} />
|
||||
{/if}
|
||||
</div>
|
|
@ -1,64 +0,0 @@
|
|||
import Combine from "../Base/Combine"
|
||||
import { FixedUiElement } from "../Base/FixedUiElement"
|
||||
import Translations from "../i18n/Translations"
|
||||
import { Utils } from "../../Utils"
|
||||
import BaseUIElement from "../BaseUIElement"
|
||||
import Img from "../Base/Img"
|
||||
import { Review } from "mangrove-reviews-typescript"
|
||||
import { Store } from "../../Logic/UIEventSource"
|
||||
|
||||
export default class SingleReview extends Combine {
|
||||
constructor(review: Review & { madeByLoggedInUser: Store<boolean> }) {
|
||||
const date = new Date(review.iat * 1000)
|
||||
const reviewAuthor =
|
||||
review.metadata.nickname ??
|
||||
(review.metadata.given_name ?? "") + (review.metadata.family_name ?? "")
|
||||
const authorElement = new FixedUiElement(reviewAuthor).SetClass("font-bold")
|
||||
|
||||
super([
|
||||
new Combine([SingleReview.GenStars(review.rating)]),
|
||||
new FixedUiElement(review.opinion),
|
||||
new Combine([
|
||||
new Combine([
|
||||
authorElement,
|
||||
review.metadata.is_affiliated
|
||||
? Translations.t.reviews.affiliated_reviewer_warning
|
||||
: "",
|
||||
]).SetStyle("margin-right: 0.5em"),
|
||||
new FixedUiElement(
|
||||
`${date.getFullYear()}-${Utils.TwoDigits(
|
||||
date.getMonth() + 1
|
||||
)}-${Utils.TwoDigits(date.getDate())} ${Utils.TwoDigits(
|
||||
date.getHours()
|
||||
)}:${Utils.TwoDigits(date.getMinutes())}`
|
||||
).SetClass("subtle"),
|
||||
]).SetClass("flex mb-4 justify-end"),
|
||||
])
|
||||
this.SetClass("block p-2 m-4 rounded-xl subtle-background review-element")
|
||||
review.madeByLoggedInUser.addCallbackAndRun((madeByUser) => {
|
||||
if (madeByUser) {
|
||||
authorElement.SetClass("thanks")
|
||||
} else {
|
||||
authorElement.RemoveClass("thanks")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
public static GenStars(rating: number): BaseUIElement {
|
||||
if (rating === undefined) {
|
||||
return Translations.t.reviews.no_rating
|
||||
}
|
||||
if (rating < 10) {
|
||||
rating = 10
|
||||
}
|
||||
const scoreTen = Math.round(rating / 10)
|
||||
return new Combine([
|
||||
...Utils.TimesT(scoreTen / 2, (_) =>
|
||||
new Img("./assets/svg/star.svg").SetClass("'h-8 w-8 md:h-12")
|
||||
),
|
||||
scoreTen % 2 == 1
|
||||
? new Img("./assets/svg/star_half.svg").SetClass("h-8 w-8 md:h-12")
|
||||
: undefined,
|
||||
]).SetClass("flex w-max")
|
||||
}
|
||||
}
|
32
src/UI/Reviews/StarElement.svelte
Normal file
32
src/UI/Reviews/StarElement.svelte
Normal file
|
@ -0,0 +1,32 @@
|
|||
<script lang="ts">
|
||||
|
||||
import ToSvelte from "../Base/ToSvelte.svelte";
|
||||
import Svg from "../../Svg";
|
||||
import { createEventDispatcher } from "svelte";
|
||||
|
||||
export let score: number;
|
||||
export let cutoff: number;
|
||||
export let starSize = "w-h h-4";
|
||||
|
||||
let dispatch = createEventDispatcher<{ hover: { score: number } }>();
|
||||
let container: HTMLElement;
|
||||
|
||||
function getScore(e: MouseEvent): number {
|
||||
const x = e.clientX - e.target.getBoundingClientRect().x;
|
||||
const w = container.getClientRects()[0]?.width;
|
||||
return (x / w) < 0.5 ? cutoff - 10 : cutoff;
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<div bind:this={container} on:click={(e) => dispatch("click", {score: getScore(e)})}
|
||||
on:mousemove={(e) => dispatch("hover", { score: getScore(e) })}>
|
||||
|
||||
{#if score >= cutoff}
|
||||
<ToSvelte construct={Svg.star_svg().SetClass(starSize)} />
|
||||
{:else if score + 10 >= cutoff}
|
||||
<ToSvelte construct={Svg.star_half_svg().SetClass(starSize)} />
|
||||
{:else}
|
||||
<ToSvelte construct={Svg.star_outline_svg().SetClass(starSize)} />
|
||||
{/if}
|
||||
</div>
|
21
src/UI/Reviews/StarsBar.svelte
Normal file
21
src/UI/Reviews/StarsBar.svelte
Normal file
|
@ -0,0 +1,21 @@
|
|||
<script lang="ts">
|
||||
import { createEventDispatcher } from "svelte";
|
||||
import StarElement from "./StarElement.svelte";
|
||||
|
||||
/**
|
||||
* Number between 0 and 100. Every 10 points, another half star is added
|
||||
*/
|
||||
export let score: number;
|
||||
let dispatch = createEventDispatcher<{ hover: number, click: number }>();
|
||||
|
||||
let cutoffs = [20,40,60,80,100]
|
||||
export let starSize = "w-h h-4"
|
||||
|
||||
</script>
|
||||
{#if score !== undefined}
|
||||
<div class="flex" on:mouseout>
|
||||
{#each cutoffs as cutoff}
|
||||
<StarElement {score} {cutoff} {starSize} on:hover on:click/>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
11
src/UI/Reviews/StarsBarIcon.svelte
Normal file
11
src/UI/Reviews/StarsBarIcon.svelte
Normal file
|
@ -0,0 +1,11 @@
|
|||
<script lang="ts">
|
||||
|
||||
import { Store } from "../../Logic/UIEventSource";
|
||||
import StarsBar from "./StarsBar.svelte";
|
||||
|
||||
export let score: Store<number>;
|
||||
</script>
|
||||
|
||||
{#if $score !== undefined && $score !== null}
|
||||
<StarsBar score={$score} />
|
||||
{/if}
|
|
@ -23,8 +23,6 @@ import { Utils } from "../Utils";
|
|||
import Wikidata, { WikidataResponse } from "../Logic/Web/Wikidata";
|
||||
import { Translation } from "./i18n/Translation";
|
||||
import Translations from "./i18n/Translations";
|
||||
import ReviewForm from "./Reviews/ReviewForm";
|
||||
import ReviewElement from "./Reviews/ReviewElement";
|
||||
import OpeningHoursVisualization from "./OpeningHours/OpeningHoursVisualization";
|
||||
import LiveQueryHandler from "../Logic/Web/LiveQueryHandler";
|
||||
import { SubtleButton } from "./Base/SubtleButton";
|
||||
|
@ -66,6 +64,9 @@ import SendEmail from "./Popup/SendEmail.svelte";
|
|||
import NearbyImages from "./Popup/NearbyImages.svelte";
|
||||
import NearbyImagesCollapsed from "./Popup/NearbyImagesCollapsed.svelte";
|
||||
import UploadImage from "./Image/UploadImage.svelte";
|
||||
import AllReviews from "./Reviews/AllReviews.svelte";
|
||||
import StarsBarIcon from "./Reviews/StarsBarIcon.svelte";
|
||||
import ReviewForm from "./Reviews/ReviewForm.svelte";
|
||||
|
||||
class NearbyImageVis implements SpecialVisualization {
|
||||
// Class must be in SpecialVisualisations due to weird cyclical import that breaks the tests
|
||||
|
@ -624,7 +625,66 @@ export default class SpecialVisualizations {
|
|||
},
|
||||
},
|
||||
{
|
||||
funcName: "reviews",
|
||||
funcName: "rating",
|
||||
docs: "Shows stars which represent the avarage rating on mangrove.reviews",
|
||||
args: [
|
||||
{
|
||||
name: "subjectKey",
|
||||
defaultValue: "name",
|
||||
doc: "The key to use to determine the subject. If specified, the subject will be <b>tags[subjectKey]</b>",
|
||||
},
|
||||
{
|
||||
name: "fallback",
|
||||
doc: "The identifier to use, if <i>tags[subjectKey]</i> as specified above is not available. This is effectively a fallback value",
|
||||
},
|
||||
],
|
||||
constr: (state, tags, args, feature, layer) => {
|
||||
const nameKey = args[0] ?? "name"
|
||||
let fallbackName = args[1]
|
||||
const reviews = FeatureReviews.construct(
|
||||
feature,
|
||||
tags,
|
||||
state.userRelatedState.mangroveIdentity,
|
||||
{
|
||||
nameKey: nameKey,
|
||||
fallbackName,
|
||||
}
|
||||
)
|
||||
return new SvelteUIElement(StarsBarIcon, {score:reviews.average, reviews, state, tags, feature, layer})
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
funcName: "create_review",
|
||||
docs: "Invites the contributor to leave a review. Somewhat small UI-element until interacted",
|
||||
args: [
|
||||
{
|
||||
name: "subjectKey",
|
||||
defaultValue: "name",
|
||||
doc: "The key to use to determine the subject. If specified, the subject will be <b>tags[subjectKey]</b>",
|
||||
},
|
||||
{
|
||||
name: "fallback",
|
||||
doc: "The identifier to use, if <i>tags[subjectKey]</i> as specified above is not available. This is effectively a fallback value",
|
||||
},
|
||||
],
|
||||
constr: (state, tags, args, feature, layer) => {
|
||||
const nameKey = args[0] ?? "name"
|
||||
let fallbackName = args[1]
|
||||
const reviews = FeatureReviews.construct(
|
||||
feature,
|
||||
tags,
|
||||
state.userRelatedState.mangroveIdentity,
|
||||
{
|
||||
nameKey: nameKey,
|
||||
fallbackName,
|
||||
}
|
||||
)
|
||||
return new SvelteUIElement(ReviewForm, {reviews, state, tags, feature, layer})
|
||||
},
|
||||
},
|
||||
{
|
||||
funcName: "list_reviews",
|
||||
docs: "Adds an overview of the mangrove-reviews of this object. Mangrove.Reviews needs - in order to identify the reviewed object - a coordinate and a name. By default, the name of the object is given, but this can be overwritten",
|
||||
example:
|
||||
"`{reviews()}` for a vanilla review, `{reviews(name, play_forest)}` to review a play forest. If a name is known, the name will be used as identifier, otherwise 'play_forest' is used",
|
||||
|
@ -639,10 +699,10 @@ export default class SpecialVisualizations {
|
|||
doc: "The identifier to use, if <i>tags[subjectKey]</i> as specified above is not available. This is effectively a fallback value",
|
||||
},
|
||||
],
|
||||
constr: (state, tags, args, feature) => {
|
||||
constr: (state, tags, args, feature, layer) => {
|
||||
const nameKey = args[0] ?? "name"
|
||||
let fallbackName = args[1]
|
||||
const mangrove = FeatureReviews.construct(
|
||||
const reviews = FeatureReviews.construct(
|
||||
feature,
|
||||
tags,
|
||||
state.userRelatedState.mangroveIdentity,
|
||||
|
@ -651,9 +711,7 @@ export default class SpecialVisualizations {
|
|||
fallbackName,
|
||||
}
|
||||
)
|
||||
|
||||
const form = new ReviewForm((r) => mangrove.createReview(r), state)
|
||||
return new ReviewElement(mangrove, form)
|
||||
return new SvelteUIElement(AllReviews, {reviews, state, tags, feature, layer})
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue