forked from MapComplete/MapComplete
Merge branch 'develop'
# Conflicts: # assets/themes/climbing/climbing.json # assets/themes/mapcomplete-changes/mapcomplete-changes.json # css/index-tailwind-output.css
This commit is contained in:
commit
ecba715265
90 changed files with 2564 additions and 2545 deletions
46
UI/AllTagsPanel.ts
Normal file
46
UI/AllTagsPanel.ts
Normal file
|
@ -0,0 +1,46 @@
|
|||
import {VariableUiElement} from "./Base/VariableUIElement";
|
||||
import {UIEventSource} from "../Logic/UIEventSource";
|
||||
import Table from "./Base/Table";
|
||||
|
||||
export class AllTagsPanel extends VariableUiElement {
|
||||
|
||||
constructor(tags: UIEventSource<any>, state?) {
|
||||
|
||||
const calculatedTags = [].concat(
|
||||
// SimpleMetaTagger.lazyTags,
|
||||
...(state?.layoutToUse?.layers?.map(l => l.calculatedTags?.map(c => c[0]) ?? []) ?? []))
|
||||
|
||||
|
||||
super(tags.map(tags => {
|
||||
const parts = [];
|
||||
for (const key in tags) {
|
||||
if (!tags.hasOwnProperty(key)) {
|
||||
continue
|
||||
}
|
||||
let v = tags[key]
|
||||
if (v === "") {
|
||||
v = "<b>empty string</b>"
|
||||
}
|
||||
parts.push([key, v ?? "<b>undefined</b>"]);
|
||||
}
|
||||
|
||||
for (const key of calculatedTags) {
|
||||
const value = tags[key]
|
||||
if (value === undefined) {
|
||||
continue
|
||||
}
|
||||
let type = "";
|
||||
if (typeof value !== "string") {
|
||||
type = " <i>" + (typeof value) + "</i>"
|
||||
}
|
||||
parts.push(["<i>" + key + "</i>", value])
|
||||
}
|
||||
|
||||
return new Table(
|
||||
["key", "value"],
|
||||
parts
|
||||
)
|
||||
.SetStyle("border: 1px solid black; border-radius: 1em;padding:1em;display:block;").SetClass("zebra-table")
|
||||
}))
|
||||
}
|
||||
}
|
|
@ -16,7 +16,7 @@ export class VariableUiElement extends BaseUIElement {
|
|||
}
|
||||
|
||||
AsMarkdown(): string {
|
||||
const d = this._contents.data;
|
||||
const d = this._contents?.data;
|
||||
if (typeof d === "string") {
|
||||
return d;
|
||||
}
|
||||
|
@ -29,7 +29,7 @@ export class VariableUiElement extends BaseUIElement {
|
|||
protected InnerConstructElement(): HTMLElement {
|
||||
const el = document.createElement("span");
|
||||
const self = this;
|
||||
this._contents.addCallbackAndRun((contents) => {
|
||||
this._contents?.addCallbackAndRun((contents) => {
|
||||
if (self.isDestroyed) {
|
||||
return true;
|
||||
}
|
||||
|
|
|
@ -94,7 +94,7 @@ export default abstract class BaseUIElement {
|
|||
* The same as 'Render', but creates a HTML element instead of the HTML representation
|
||||
*/
|
||||
public ConstructElement(): HTMLElement {
|
||||
if (Utils.runningFromConsole) {
|
||||
if (typeof window === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
|
|
@ -20,6 +20,7 @@ import {QueryParameters} from "../../Logic/Web/QueryParameters";
|
|||
import {TagUtils} from "../../Logic/Tags/TagUtils";
|
||||
import {InputElement} from "../Input/InputElement";
|
||||
import {DropDown} from "../Input/DropDown";
|
||||
import {UIElement} from "../UIElement";
|
||||
|
||||
export default class FilterView extends VariableUiElement {
|
||||
constructor(filteredLayer: UIEventSource<FilteredLayer[]>,
|
||||
|
@ -33,7 +34,7 @@ export default class FilterView extends VariableUiElement {
|
|||
filteredLayer.map((filteredLayers) => {
|
||||
// Create the views which toggle layers (and filters them) ...
|
||||
let elements = filteredLayers
|
||||
?.map(l => FilterView.createOneFilteredLayerElement(l)?.SetClass("filter-panel"))
|
||||
?.map(l => FilterView.createOneFilteredLayerElement(l, State.state)?.SetClass("filter-panel"))
|
||||
?.filter(l => l !== undefined)
|
||||
elements[0].SetClass("first-filter-panel")
|
||||
|
||||
|
@ -87,10 +88,14 @@ export default class FilterView extends VariableUiElement {
|
|||
);
|
||||
}
|
||||
|
||||
private static createOneFilteredLayerElement(filteredLayer: FilteredLayer) {
|
||||
private static createOneFilteredLayerElement(filteredLayer: FilteredLayer, state: {featureSwitchIsDebugging: UIEventSource<boolean>}) {
|
||||
if (filteredLayer.layerDef.name === undefined) {
|
||||
// Name is not defined: we hide this one
|
||||
return undefined;
|
||||
return new Toggle(
|
||||
filteredLayer?.layerDef?.description?.Clone()?.SetClass("subtle") ,
|
||||
undefined,
|
||||
state?.featureSwitchIsDebugging
|
||||
);
|
||||
}
|
||||
const iconStyle = "width:1.5rem;height:1.5rem;margin-left:1.25rem;flex-shrink: 0;";
|
||||
|
||||
|
|
|
@ -44,38 +44,37 @@ export default class SearchAndGo extends Combine {
|
|||
);
|
||||
|
||||
// Triggered by 'enter' or onclick
|
||||
function runSearch() {
|
||||
async function runSearch() {
|
||||
const searchString = searchField.GetValue().data;
|
||||
if (searchString === undefined || searchString === "") {
|
||||
return;
|
||||
}
|
||||
searchField.GetValue().setData("");
|
||||
placeholder.setData(Translations.t.general.search.searching);
|
||||
Geocoding.Search(
|
||||
searchString,
|
||||
(result) => {
|
||||
console.log("Search result", result);
|
||||
if (result.length == 0) {
|
||||
placeholder.setData(Translations.t.general.search.nothing);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
|
||||
const poi = result[0];
|
||||
const bb = poi.boundingbox;
|
||||
const bounds: [[number, number], [number, number]] = [
|
||||
[bb[0], bb[2]],
|
||||
[bb[1], bb[3]],
|
||||
];
|
||||
state.selectedElement.setData(undefined);
|
||||
Hash.hash.setData(poi.osm_type + "/" + poi.osm_id);
|
||||
state.leafletMap.data.fitBounds(bounds);
|
||||
placeholder.setData(Translations.t.general.search.search);
|
||||
},
|
||||
() => {
|
||||
searchField.GetValue().setData("");
|
||||
placeholder.setData(Translations.t.general.search.error);
|
||||
const result = await Geocoding.Search(searchString);
|
||||
|
||||
console.log("Search result", result);
|
||||
if (result.length == 0) {
|
||||
placeholder.setData(Translations.t.general.search.nothing);
|
||||
return;
|
||||
}
|
||||
);
|
||||
|
||||
const poi = result[0];
|
||||
const bb = poi.boundingbox;
|
||||
const bounds: [[number, number], [number, number]] = [
|
||||
[bb[0], bb[2]],
|
||||
[bb[1], bb[3]],
|
||||
];
|
||||
state.selectedElement.setData(undefined);
|
||||
Hash.hash.setData(poi.osm_type + "/" + poi.osm_id);
|
||||
state.leafletMap.data.fitBounds(bounds);
|
||||
placeholder.setData(Translations.t.general.search.search)
|
||||
}catch(e){
|
||||
searchField.GetValue().setData("");
|
||||
placeholder.setData(Translations.t.general.search.error);
|
||||
}
|
||||
}
|
||||
|
||||
searchField.enterPressed.addCallback(runSearch);
|
||||
|
|
|
@ -55,7 +55,7 @@ export default class DeleteImage extends Toggle {
|
|||
tags.map(tags => (tags[key] ?? "") !== "")
|
||||
),
|
||||
undefined /*Login (and thus editing) is disabled*/,
|
||||
state.osmConnection.isLoggedIn
|
||||
state?.osmConnection?.isLoggedIn
|
||||
)
|
||||
this.SetClass("cursor-pointer")
|
||||
}
|
||||
|
|
|
@ -112,7 +112,7 @@ export class ImageUploadFlow extends Toggle {
|
|||
}
|
||||
|
||||
|
||||
const title = matchingLayer?.title?.GetRenderValue(tags)?.ConstructElement()?.innerText ?? tags.name ?? "Unknown area";
|
||||
const title = matchingLayer?.title?.GetRenderValue(tags)?.Subs(tags)?.ConstructElement()?.innerText ?? tags.name ?? "https//osm.org/"+tags.id;
|
||||
const description = [
|
||||
"author:" + state.osmConnection.userDetails.data.name,
|
||||
"license:" + license,
|
||||
|
@ -169,7 +169,7 @@ export class ImageUploadFlow extends Toggle {
|
|||
state?.osmConnection?.isLoggedIn
|
||||
),
|
||||
undefined /* Nothing as the user badge is disabled*/,
|
||||
state.featureSwitchUserbadge
|
||||
state?.featureSwitchUserbadge
|
||||
)
|
||||
|
||||
}
|
||||
|
|
|
@ -44,6 +44,47 @@ interface NoteState {
|
|||
status: "imported" | "already_mapped" | "invalid" | "closed" | "not_found" | "open" | "has_comments"
|
||||
}
|
||||
|
||||
class DownloadStatisticsButton extends SubtleButton {
|
||||
constructor(states: NoteState[][]) {
|
||||
super(Svg.statistics_svg(), "Download statistics");
|
||||
this.onClick(() => {
|
||||
|
||||
const st: NoteState[] = [].concat(...states)
|
||||
|
||||
const fields = [
|
||||
"id",
|
||||
"status",
|
||||
"theme",
|
||||
"date_created",
|
||||
"date_closed",
|
||||
"days_open",
|
||||
"intro",
|
||||
"...comments"
|
||||
]
|
||||
const values : string[][] = st.map(note => {
|
||||
|
||||
|
||||
return [note.props.id+"",
|
||||
note.status,
|
||||
note.theme,
|
||||
note.props.date_created?.substr(0, note.props.date_created.length - 3),
|
||||
note.props.closed_at?.substr(0, note.props.closed_at.length - 3) ?? "",
|
||||
JSON.stringify( note.intro),
|
||||
...note.props.comments.map(c => JSON.stringify(c.user)+": "+JSON.stringify(c.text))
|
||||
]
|
||||
})
|
||||
|
||||
Utils.offerContentsAsDownloadableFile(
|
||||
[fields, ...values].map(c => c.join(", ")).join("\n"),
|
||||
"mapcomplete_import_notes_overview.csv",
|
||||
{
|
||||
mimetype: "text/csv"
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
class MassAction extends Combine {
|
||||
constructor(state: UserRelatedState, props: NoteProperties[]) {
|
||||
const textField = ValidatedTextField.ForType("text").ConstructInputElement()
|
||||
|
@ -303,7 +344,9 @@ class ImportInspector extends VariableUiElement {
|
|||
contents.push(accordeon)
|
||||
const content = new Combine(contents)
|
||||
return new LeftIndex(
|
||||
[new TableOfContents(content, {noTopLevel: true, maxDepth: 1}).SetClass("subtle")],
|
||||
[new TableOfContents(content, {noTopLevel: true, maxDepth: 1}).SetClass("subtle"),
|
||||
new DownloadStatisticsButton(perBatch)
|
||||
],
|
||||
content
|
||||
)
|
||||
|
||||
|
|
|
@ -21,9 +21,9 @@ import {VariableUiElement} from "../Base/VariableUIElement";
|
|||
import {FixedUiElement} from "../Base/FixedUiElement";
|
||||
import {FlowStep} from "./FlowStep";
|
||||
import ScrollableFullScreen from "../Base/ScrollableFullScreen";
|
||||
import {AllTagsPanel} from "../SpecialVisualizations";
|
||||
import Title from "../Base/Title";
|
||||
import CheckBoxes from "../Input/Checkboxes";
|
||||
import {AllTagsPanel} from "../AllTagsPanel";
|
||||
|
||||
class PreviewPanel extends ScrollableFullScreen {
|
||||
|
||||
|
|
|
@ -13,7 +13,7 @@ export default class Toggle extends VariableUiElement {
|
|||
|
||||
constructor(showEnabled: string | BaseUIElement, showDisabled: string | BaseUIElement, isEnabled: UIEventSource<boolean> = new UIEventSource<boolean>(false)) {
|
||||
super(
|
||||
isEnabled.map(isEnabled => isEnabled ? showEnabled : showDisabled)
|
||||
isEnabled?.map(isEnabled => isEnabled ? showEnabled : showDisabled)
|
||||
);
|
||||
this.isEnabled = isEnabled
|
||||
}
|
||||
|
|
|
@ -250,13 +250,15 @@ class WikidataTextField extends TextFieldDef {
|
|||
["subarg", "doc"],
|
||||
[["removePrefixes", "remove these snippets of text from the start of the passed string to search"],
|
||||
["removePostfixes", "remove these snippets of text from the end of the passed string to search"],
|
||||
["instanceOf","A list of Q-identifier which indicates that the search results _must_ be an entity of this type, e.g. [`Q5`](https://www.wikidata.org/wiki/Q5) for humans"],
|
||||
["notInstanceof","A list of Q-identifiers which indicates that the search results _must not_ be an entity of this type, e.g. [`Q79007`](https://www.wikidata.org/wiki/Q79007) to filter away all streets from the search results"]
|
||||
]
|
||||
)])
|
||||
]]),
|
||||
new Title("Example usage"),
|
||||
`The following is the 'freeform'-part of a layer config which will trigger a search for the wikidata item corresponding with the name of the selected feature. It will also remove '-street', '-square', ... if found at the end of the name
|
||||
|
||||
\`\`\`
|
||||
\`\`\`json
|
||||
"freeform": {
|
||||
"key": "name:etymology:wikidata",
|
||||
"type": "wikidata",
|
||||
|
@ -269,11 +271,29 @@ class WikidataTextField extends TextFieldDef {
|
|||
"path",
|
||||
"square",
|
||||
"plaza",
|
||||
]
|
||||
],
|
||||
"#": "Remove streets and parks from the search results:"
|
||||
"notInstanceOf": ["Q79007","Q22698"]
|
||||
}
|
||||
|
||||
]
|
||||
}
|
||||
\`\`\``
|
||||
\`\`\`
|
||||
|
||||
Another example is to search for species and trees:
|
||||
|
||||
\`\`\`json
|
||||
"freeform": {
|
||||
"key": "species:wikidata",
|
||||
"type": "wikidata",
|
||||
"helperArgs": [
|
||||
"species",
|
||||
{
|
||||
"instanceOf": [10884, 16521]
|
||||
}]
|
||||
}
|
||||
\`\`\`
|
||||
`
|
||||
]));
|
||||
}
|
||||
|
||||
|
@ -304,9 +324,9 @@ class WikidataTextField extends TextFieldDef {
|
|||
const args = inputHelperOptions.args ?? []
|
||||
const searchKey = args[0] ?? "name"
|
||||
|
||||
let searchFor = <string>inputHelperOptions.feature?.properties[searchKey]?.toLowerCase()
|
||||
let searchFor = <string>(inputHelperOptions.feature?.properties[searchKey]?.toLowerCase() ?? "")
|
||||
|
||||
const options = args[1]
|
||||
const options: any = args[1]
|
||||
if (searchFor !== undefined && options !== undefined) {
|
||||
const prefixes = <string[]>options["removePrefixes"]
|
||||
const postfixes = <string[]>options["removePostfixes"]
|
||||
|
@ -325,10 +345,18 @@ class WikidataTextField extends TextFieldDef {
|
|||
}
|
||||
|
||||
}
|
||||
|
||||
let instanceOf : number[] = Utils.NoNull((options?.instanceOf ?? []).map(i => Wikidata.QIdToNumber(i)))
|
||||
let notInstanceOf : number[] = Utils.NoNull((options?.notInstanceOf ?? []).map(i => Wikidata.QIdToNumber(i)))
|
||||
|
||||
console.log("Instance of", instanceOf)
|
||||
|
||||
|
||||
return new WikidataSearchBox({
|
||||
value: currentValue,
|
||||
searchText: new UIEventSource<string>(searchFor)
|
||||
searchText: new UIEventSource<string>(searchFor),
|
||||
instanceOf,
|
||||
notInstanceOf
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
import {Utils} from "../../Utils";
|
||||
import opening_hours from "opening_hours";
|
||||
|
||||
export interface OpeningHour {
|
||||
weekday: number, // 0 is monday, 1 is tuesday, ...
|
||||
|
@ -458,6 +459,17 @@ export class OH {
|
|||
return [changeHours, changeHourText]
|
||||
}
|
||||
|
||||
public static CreateOhObject(tags: object & {_lat: number, _lon: number, _country?: string}, textToParse: string){
|
||||
// noinspection JSPotentiallyInvalidConstructorUsage
|
||||
return new opening_hours(textToParse, {
|
||||
lat: tags._lat,
|
||||
lon: tags._lon,
|
||||
address: {
|
||||
country_code: tags._country
|
||||
},
|
||||
}, {tag_key: "opening_hours"});
|
||||
}
|
||||
|
||||
/*
|
||||
Calculates when the business is opened (or on holiday) between two dates.
|
||||
Returns a matrix of ranges, where [0] is a list of ranges when it is opened on monday, [1] is a list of ranges for tuesday, ...
|
||||
|
@ -599,6 +611,12 @@ export class OH {
|
|||
}
|
||||
return ohs;
|
||||
}
|
||||
public static getMondayBefore(d) {
|
||||
d = new Date(d);
|
||||
const day = d.getDay();
|
||||
const diff = d.getDate() - day + (day == 0 ? -6 : 1); // adjust when day is sunday
|
||||
return new Date(d.setDate(diff));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -4,7 +4,6 @@ import {FixedUiElement} from "../Base/FixedUiElement";
|
|||
import {OH} from "./OpeningHours";
|
||||
import Translations from "../i18n/Translations";
|
||||
import Constants from "../../Models/Constants";
|
||||
import opening_hours from "opening_hours";
|
||||
import BaseUIElement from "../BaseUIElement";
|
||||
import Toggle from "../Input/Toggle";
|
||||
import {VariableUiElement} from "../Base/VariableUIElement";
|
||||
|
@ -24,7 +23,6 @@ export default class OpeningHoursVisualization extends Toggle {
|
|||
]
|
||||
|
||||
constructor(tags: UIEventSource<any>, state: { osmConnection?: OsmConnection }, key: string, prefix = "", postfix = "") {
|
||||
const tagsDirect = tags.data;
|
||||
const ohTable = new VariableUiElement(tags
|
||||
.map(tags => {
|
||||
const value: string = tags[key];
|
||||
|
@ -41,16 +39,8 @@ export default class OpeningHoursVisualization extends Toggle {
|
|||
return new FixedUiElement("No opening hours defined with key " + key).SetClass("alert")
|
||||
}
|
||||
try {
|
||||
// noinspection JSPotentiallyInvalidConstructorUsage
|
||||
const oh = new opening_hours(ohtext, {
|
||||
lat: tagsDirect._lat,
|
||||
lon: tagsDirect._lon,
|
||||
address: {
|
||||
country_code: tagsDirect._country
|
||||
},
|
||||
}, {tag_key: "opening_hours"});
|
||||
|
||||
return OpeningHoursVisualization.CreateFullVisualisation(oh)
|
||||
return OpeningHoursVisualization.CreateFullVisualisation(
|
||||
OH.CreateOhObject(tags.data, ohtext))
|
||||
} catch (e) {
|
||||
console.warn(e, e.stack);
|
||||
return new Combine([Translations.t.general.opening_hours.error_loading,
|
||||
|
@ -78,7 +68,7 @@ export default class OpeningHoursVisualization extends Toggle {
|
|||
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
const lastMonday = OpeningHoursVisualization.getMonday(today);
|
||||
const lastMonday = OH.getMondayBefore(today);
|
||||
const nextSunday = new Date(lastMonday);
|
||||
nextSunday.setDate(nextSunday.getDate() + 7);
|
||||
|
||||
|
@ -283,11 +273,5 @@ export default class OpeningHoursVisualization extends Toggle {
|
|||
return Translations.t.general.opening_hours.closed_until.Subs({date: willOpenAt})
|
||||
}
|
||||
|
||||
private static getMonday(d) {
|
||||
d = new Date(d);
|
||||
const day = d.getDay();
|
||||
const diff = d.getDate() - day + (day == 0 ? -6 : 1); // adjust when day is sunday
|
||||
return new Date(d.setDate(diff));
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -11,7 +11,7 @@ import {SaveButton} from "./SaveButton";
|
|||
import {VariableUiElement} from "../Base/VariableUIElement";
|
||||
import Translations from "../i18n/Translations";
|
||||
import {FixedUiElement} from "../Base/FixedUiElement";
|
||||
import {Translation} from "../i18n/Translation";
|
||||
import {Translation, TypedTranslation} from "../i18n/Translation";
|
||||
import Constants from "../../Models/Constants";
|
||||
import {SubstitutedTranslation} from "../SubstitutedTranslation";
|
||||
import {TagsFilter} from "../../Logic/Tags/TagsFilter";
|
||||
|
@ -51,7 +51,7 @@ export default class TagRenderingQuestion extends Combine {
|
|||
|
||||
const applicableMappingsSrc =
|
||||
UIEventSource.ListStabilized(tags.map(tags => {
|
||||
const applicableMappings: { if: TagsFilter, icon?: string, then: any, ifnot?: TagsFilter, addExtraTags: Tag[] }[] = []
|
||||
const applicableMappings: { if: TagsFilter, icon?: string, then: TypedTranslation<object>, ifnot?: TagsFilter, addExtraTags: Tag[] }[] = []
|
||||
for (const mapping of configuration.mappings ?? []) {
|
||||
if (mapping.hideInAnswer === true) {
|
||||
continue
|
||||
|
@ -158,7 +158,7 @@ export default class TagRenderingQuestion extends Combine {
|
|||
private static GenerateInputElement(
|
||||
state,
|
||||
configuration: TagRenderingConfig,
|
||||
applicableMappings: { if: TagsFilter, then: any, icon?: string, ifnot?: TagsFilter, addExtraTags: Tag[] }[],
|
||||
applicableMappings: { if: TagsFilter, then: TypedTranslation<object>, icon?: string, ifnot?: TagsFilter, addExtraTags: Tag[] }[],
|
||||
applicableUnit: Unit,
|
||||
tagsSource: UIEventSource<any>,
|
||||
feedback: UIEventSource<Translation>
|
||||
|
@ -207,7 +207,7 @@ export default class TagRenderingQuestion extends Combine {
|
|||
applicableMappings.map((mapping, i) => {
|
||||
return {
|
||||
value: new And([mapping.if, ...allIfNotsExcept(i)]),
|
||||
shown: Translations.T(mapping.then)
|
||||
shown: mapping.then.Subs(tagsSource.data)
|
||||
}
|
||||
})
|
||||
)
|
||||
|
|
|
@ -1,50 +1,5 @@
|
|||
import {UIEventSource} from "../../Logic/UIEventSource";
|
||||
import LayerConfig from "../../Models/ThemeConfig/LayerConfig";
|
||||
import {ShowDataLayerOptions} from "./ShowDataLayerOptions";
|
||||
import {ElementStorage} from "../../Logic/ElementStorage";
|
||||
import RenderingMultiPlexerFeatureSource from "../../Logic/FeatureSource/Sources/RenderingMultiPlexerFeatureSource";
|
||||
import ScrollableFullScreen from "../Base/ScrollableFullScreen";
|
||||
/*
|
||||
// import 'leaflet-polylineoffset';
|
||||
We don't actually import it here. It is imported in the 'MinimapImplementation'-class, which'll result in a patched 'L' object.
|
||||
Even though actually importing this here would seem cleaner, we don't do this as this breaks some scripts:
|
||||
- Scripts are ran in ts-node
|
||||
- ts-node doesn't define the 'window'-object
|
||||
- Importing this will execute some code which needs the window object
|
||||
|
||||
*/
|
||||
|
||||
/**
|
||||
* The data layer shows all the given geojson elements with the appropriate icon etc
|
||||
*/
|
||||
export default class ShowDataLayer {
|
||||
|
||||
private static dataLayerIds = 0
|
||||
private readonly _leafletMap: UIEventSource<L.Map>;
|
||||
private readonly _enablePopups: boolean;
|
||||
private readonly _features: RenderingMultiPlexerFeatureSource
|
||||
private readonly _layerToShow: LayerConfig;
|
||||
private readonly _selectedElement: UIEventSource<any>
|
||||
private readonly allElements: ElementStorage
|
||||
// Used to generate a fresh ID when needed
|
||||
private _cleanCount = 0;
|
||||
private geoLayer = undefined;
|
||||
|
||||
/**
|
||||
* A collection of functions to call when the current geolayer is unregistered
|
||||
*/
|
||||
private unregister: (() => void)[] = [];
|
||||
private isDirty = false;
|
||||
/**
|
||||
* If the selected element triggers, this is used to lookup the correct layer and to open the popup
|
||||
* Used to avoid a lot of callbacks on the selected element
|
||||
*
|
||||
* Note: the key of this dictionary is 'feature.properties.id+features.geometry.type' as one feature might have multiple presentations
|
||||
* @private
|
||||
*/
|
||||
private readonly leafletLayersPerId = new Map<string, { feature: any, leafletlayer: any }>()
|
||||
private readonly showDataLayerid: number;
|
||||
private readonly createPopup: (tags: UIEventSource<any>, layer: LayerConfig) => ScrollableFullScreen
|
||||
|
||||
/**
|
||||
* Creates a datalayer.
|
||||
|
@ -52,299 +7,10 @@ export default class ShowDataLayer {
|
|||
* If 'createPopup' is set, this function is called every time that 'popupOpen' is called
|
||||
* @param options
|
||||
*/
|
||||
constructor(options: ShowDataLayerOptions & { layerToShow: LayerConfig }) {
|
||||
this._leafletMap = options.leafletMap;
|
||||
this.showDataLayerid = ShowDataLayer.dataLayerIds;
|
||||
ShowDataLayer.dataLayerIds++
|
||||
if (options.features === undefined) {
|
||||
console.error("Invalid ShowDataLayer invocation: options.features is undefed")
|
||||
throw "Invalid ShowDataLayer invocation: options.features is undefed"
|
||||
}
|
||||
this._features = new RenderingMultiPlexerFeatureSource(options.features, options.layerToShow);
|
||||
this._layerToShow = options.layerToShow;
|
||||
this._selectedElement = options.selectedElement
|
||||
this.allElements = options.state?.allElements;
|
||||
this.createPopup = undefined;
|
||||
this._enablePopups = options.popup !== undefined;
|
||||
if (options.popup !== undefined) {
|
||||
this.createPopup = options.popup
|
||||
}
|
||||
const self = this;
|
||||
|
||||
options.leafletMap.addCallback(_ => {
|
||||
return self.update(options)
|
||||
}
|
||||
);
|
||||
|
||||
this._features.features.addCallback(_ => self.update(options));
|
||||
options.doShowLayer?.addCallback(doShow => {
|
||||
const mp = options.leafletMap.data;
|
||||
if (mp === null) {
|
||||
self.Destroy()
|
||||
return true;
|
||||
}
|
||||
if (mp == undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (doShow) {
|
||||
if (self.isDirty) {
|
||||
return self.update(options)
|
||||
} else {
|
||||
mp.addLayer(this.geoLayer)
|
||||
}
|
||||
} else {
|
||||
if (this.geoLayer !== undefined) {
|
||||
mp.removeLayer(this.geoLayer)
|
||||
this.unregister.forEach(f => f())
|
||||
this.unregister = []
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
|
||||
this._selectedElement?.addCallbackAndRunD(selected => {
|
||||
self.openPopupOfSelectedElement(selected)
|
||||
})
|
||||
|
||||
this.update(options)
|
||||
|
||||
}
|
||||
|
||||
private Destroy() {
|
||||
this.unregister.forEach(f => f())
|
||||
}
|
||||
|
||||
private openPopupOfSelectedElement(selected) {
|
||||
if (selected === undefined) {
|
||||
return
|
||||
}
|
||||
if (this._leafletMap.data === undefined) {
|
||||
return;
|
||||
}
|
||||
const v = this.leafletLayersPerId.get(selected.properties.id + selected.geometry.type)
|
||||
if (v === undefined) {
|
||||
return;
|
||||
}
|
||||
const leafletLayer = v.leafletlayer
|
||||
const feature = v.feature
|
||||
if (leafletLayer.getPopup().isOpen()) {
|
||||
return;
|
||||
}
|
||||
if (selected.properties.id !== feature.properties.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (feature.id !== feature.properties.id) {
|
||||
// Probably a feature which has renamed
|
||||
// the feature might have as id 'node/-1' and as 'feature.properties.id' = 'the newly assigned id'. That is no good too
|
||||
console.log("Not opening the popup for", feature, "as probably renamed")
|
||||
return;
|
||||
}
|
||||
if (selected.geometry.type === feature.geometry.type // If a feature is rendered both as way and as point, opening one popup might trigger the other to open, which might trigger the one to open again
|
||||
) {
|
||||
leafletLayer.openPopup()
|
||||
}
|
||||
}
|
||||
|
||||
private update(options: ShowDataLayerOptions): boolean {
|
||||
if (this._features.features.data === undefined) {
|
||||
return;
|
||||
}
|
||||
this.isDirty = true;
|
||||
if (options?.doShowLayer?.data === false) {
|
||||
return;
|
||||
}
|
||||
const mp = options.leafletMap.data;
|
||||
|
||||
if (mp === null) {
|
||||
return true; // Unregister as the map has been destroyed
|
||||
}
|
||||
if (mp === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._cleanCount++
|
||||
// clean all the old stuff away, if any
|
||||
if (this.geoLayer !== undefined) {
|
||||
mp.removeLayer(this.geoLayer);
|
||||
}
|
||||
|
||||
const self = this;
|
||||
const data = {
|
||||
type: "FeatureCollection",
|
||||
features: []
|
||||
}
|
||||
// @ts-ignore
|
||||
this.geoLayer = L.geoJSON(data, {
|
||||
style: feature => self.createStyleFor(feature),
|
||||
pointToLayer: (feature, latLng) => self.pointToLayer(feature, latLng),
|
||||
onEachFeature: (feature, leafletLayer) => self.postProcessFeature(feature, leafletLayer)
|
||||
});
|
||||
|
||||
const selfLayer = this.geoLayer;
|
||||
const allFeats = this._features.features.data;
|
||||
for (const feat of allFeats) {
|
||||
if (feat === undefined) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
if (feat.geometry.type === "LineString") {
|
||||
const coords = L.GeoJSON.coordsToLatLngs(feat.geometry.coordinates)
|
||||
const tagsSource = this.allElements?.addOrGetElement(feat) ?? new UIEventSource<any>(feat.properties);
|
||||
let offsettedLine;
|
||||
tagsSource
|
||||
.map(tags => this._layerToShow.lineRendering[feat.lineRenderingIndex].GenerateLeafletStyle(tags), [], undefined, true)
|
||||
.withEqualityStabilized((a, b) => {
|
||||
if (a === b) {
|
||||
return true
|
||||
}
|
||||
if (a === undefined || b === undefined) {
|
||||
return false
|
||||
}
|
||||
return a.offset === b.offset && a.color === b.color && a.weight === b.weight && a.dashArray === b.dashArray
|
||||
})
|
||||
.addCallbackAndRunD(lineStyle => {
|
||||
if (offsettedLine !== undefined) {
|
||||
self.geoLayer.removeLayer(offsettedLine)
|
||||
}
|
||||
// @ts-ignore
|
||||
offsettedLine = L.polyline(coords, lineStyle);
|
||||
this.postProcessFeature(feat, offsettedLine)
|
||||
offsettedLine.addTo(this.geoLayer)
|
||||
|
||||
// If 'self.geoLayer' is not the same as the layer the feature is added to, we can safely remove this callback
|
||||
return self.geoLayer !== selfLayer
|
||||
})
|
||||
} else {
|
||||
this.geoLayer.addData(feat);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Could not add ", feat, "to the geojson layer in leaflet due to", e, e.stack)
|
||||
}
|
||||
}
|
||||
|
||||
if (options.zoomToFeatures ?? false) {
|
||||
if (this.geoLayer.getLayers().length > 0) {
|
||||
try {
|
||||
const bounds = this.geoLayer.getBounds()
|
||||
mp.fitBounds(bounds, {animate: false})
|
||||
} catch (e) {
|
||||
console.debug("Invalid bounds", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (options.doShowLayer?.data ?? true) {
|
||||
mp.addLayer(this.geoLayer)
|
||||
}
|
||||
this.isDirty = false;
|
||||
this.openPopupOfSelectedElement(this._selectedElement?.data)
|
||||
}
|
||||
|
||||
|
||||
private createStyleFor(feature) {
|
||||
const tagsSource = this.allElements?.addOrGetElement(feature) ?? new UIEventSource<any>(feature.properties);
|
||||
// Every object is tied to exactly one layer
|
||||
const layer = this._layerToShow
|
||||
|
||||
const pointRenderingIndex = feature.pointRenderingIndex
|
||||
const lineRenderingIndex = feature.lineRenderingIndex
|
||||
|
||||
if (pointRenderingIndex !== undefined) {
|
||||
const style = layer.mapRendering[pointRenderingIndex].GenerateLeafletStyle(tagsSource, this._enablePopups)
|
||||
return {
|
||||
icon: style
|
||||
}
|
||||
}
|
||||
if (lineRenderingIndex !== undefined) {
|
||||
return layer.lineRendering[lineRenderingIndex].GenerateLeafletStyle(tagsSource.data)
|
||||
}
|
||||
|
||||
throw "Neither lineRendering nor mapRendering defined for " + feature
|
||||
}
|
||||
|
||||
private pointToLayer(feature, latLng): L.Layer {
|
||||
// Leaflet cannot handle geojson points natively
|
||||
// We have to convert them to the appropriate icon
|
||||
// Click handling is done in the next step
|
||||
|
||||
const layer: LayerConfig = this._layerToShow
|
||||
if (layer === undefined) {
|
||||
return;
|
||||
}
|
||||
let tagSource = this.allElements?.getEventSourceById(feature.properties.id) ?? new UIEventSource<any>(feature.properties)
|
||||
const clickable = !(layer.title === undefined && (layer.tagRenderings ?? []).length === 0) && this._enablePopups
|
||||
let style: any = layer.mapRendering[feature.pointRenderingIndex].GenerateLeafletStyle(tagSource, clickable);
|
||||
const baseElement = style.html;
|
||||
if (!this._enablePopups) {
|
||||
baseElement.SetStyle("cursor: initial !important")
|
||||
}
|
||||
style.html = style.html.ConstructElement()
|
||||
return L.marker(latLng, {
|
||||
icon: L.divIcon(style)
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Post processing - basically adding the popup
|
||||
* @param feature
|
||||
* @param leafletLayer
|
||||
* @private
|
||||
*/
|
||||
private postProcessFeature(feature, leafletLayer: L.Layer) {
|
||||
const layer: LayerConfig = this._layerToShow
|
||||
if (layer.title === undefined || !this._enablePopups) {
|
||||
// No popup action defined -> Don't do anything
|
||||
// or probably a map in the popup - no popups needed!
|
||||
return;
|
||||
}
|
||||
|
||||
const popup = L.popup({
|
||||
autoPan: true,
|
||||
closeOnEscapeKey: true,
|
||||
closeButton: false,
|
||||
autoPanPaddingTopLeft: [15, 15],
|
||||
|
||||
}, leafletLayer);
|
||||
|
||||
leafletLayer.bindPopup(popup);
|
||||
|
||||
let infobox: ScrollableFullScreen = undefined;
|
||||
const id = `popup-${feature.properties.id}-${feature.geometry.type}-${this.showDataLayerid}-${this._cleanCount}-${feature.pointRenderingIndex ?? feature.lineRenderingIndex}-${feature.multiLineStringIndex ?? ""}`
|
||||
popup.setContent(`<div style='height: 65vh' id='${id}'>Popup for ${feature.properties.id} ${feature.geometry.type} ${id} is loading</div>`)
|
||||
const createpopup = this.createPopup;
|
||||
leafletLayer.on("popupopen", () => {
|
||||
if (infobox === undefined) {
|
||||
const tags = this.allElements?.getEventSourceById(feature.properties.id) ?? new UIEventSource<any>(feature.properties);
|
||||
infobox = createpopup(tags, layer);
|
||||
|
||||
infobox.isShown.addCallback(isShown => {
|
||||
if (!isShown) {
|
||||
leafletLayer.closePopup()
|
||||
}
|
||||
});
|
||||
}
|
||||
infobox.AttachTo(id)
|
||||
infobox.Activate();
|
||||
this.unregister.push(() => {
|
||||
console.log("Destroying infobox")
|
||||
infobox.Destroy();
|
||||
})
|
||||
if (this._selectedElement?.data?.properties?.id !== feature.properties.id) {
|
||||
this._selectedElement?.setData(feature)
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
|
||||
// Add the feature to the index to open the popup when needed
|
||||
this.leafletLayersPerId.set(feature.properties.id + feature.geometry.type, {
|
||||
feature: feature,
|
||||
leafletlayer: leafletLayer
|
||||
})
|
||||
constructor(options) {
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -24,7 +24,6 @@ import ShowDataMultiLayer from "./ShowDataLayer/ShowDataMultiLayer";
|
|||
import Minimap from "./Base/Minimap";
|
||||
import AllImageProviders from "../Logic/ImageProviders/AllImageProviders";
|
||||
import WikipediaBox from "./Wikipedia/WikipediaBox";
|
||||
import SimpleMetaTagger from "../Logic/SimpleMetaTagger";
|
||||
import MultiApply from "./Popup/MultiApply";
|
||||
import ShowDataLayer from "./ShowDataLayer/ShowDataLayer";
|
||||
import {SubtleButton} from "./Base/SubtleButton";
|
||||
|
@ -46,6 +45,9 @@ import {LoginToggle} from "./Popup/LoginButton";
|
|||
import {start} from "repl";
|
||||
import {SubstitutedTranslation} from "./SubstitutedTranslation";
|
||||
import {TextField} from "./Input/TextField";
|
||||
import Wikidata, {WikidataResponse} from "../Logic/Web/Wikidata";
|
||||
import {Translation} from "./i18n/Translation";
|
||||
import {AllTagsPanel} from "./AllTagsPanel";
|
||||
|
||||
export interface SpecialVisualization {
|
||||
funcName: string,
|
||||
|
@ -56,45 +58,6 @@ export interface SpecialVisualization {
|
|||
getLayerDependencies?: (argument: string[]) => string[]
|
||||
}
|
||||
|
||||
export class AllTagsPanel extends VariableUiElement {
|
||||
|
||||
constructor(tags: UIEventSource<any>, state?) {
|
||||
|
||||
const calculatedTags = [].concat(
|
||||
SimpleMetaTagger.lazyTags,
|
||||
...(state?.layoutToUse?.layers?.map(l => l.calculatedTags?.map(c => c[0]) ?? []) ?? []))
|
||||
|
||||
|
||||
super(tags.map(tags => {
|
||||
const parts = [];
|
||||
for (const key in tags) {
|
||||
if (!tags.hasOwnProperty(key)) {
|
||||
continue
|
||||
}
|
||||
let v = tags[key]
|
||||
if (v === "") {
|
||||
v = "<b>empty string</b>"
|
||||
}
|
||||
parts.push([key, v ?? "<b>undefined</b>"]);
|
||||
}
|
||||
|
||||
for (const key of calculatedTags) {
|
||||
const value = tags[key]
|
||||
if (value === undefined) {
|
||||
continue
|
||||
}
|
||||
parts.push(["<i>" + key + "</i>", value])
|
||||
}
|
||||
|
||||
return new Table(
|
||||
["key", "value"],
|
||||
parts
|
||||
)
|
||||
.SetStyle("border: 1px solid black; border-radius: 1em;padding:1em;display:block;").SetClass("zebra-table")
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
class CloseNoteButton implements SpecialVisualization {
|
||||
public readonly funcName = "close_note"
|
||||
public readonly docs = "Button to close a note. A predifined text can be defined to close the note with. If the note is already closed, will show a small text."
|
||||
|
@ -159,19 +122,19 @@ class CloseNoteButton implements SpecialVisualization {
|
|||
tags.ping()
|
||||
})
|
||||
})
|
||||
|
||||
if((params.minZoom??"") !== "" && !isNaN(Number(params.minZoom))){
|
||||
closeButton = new Toggle(
|
||||
|
||||
if ((params.minZoom ?? "") !== "" && !isNaN(Number(params.minZoom))) {
|
||||
closeButton = new Toggle(
|
||||
closeButton,
|
||||
params.zoomButton ?? "",
|
||||
state. locationControl.map(l => l.zoom >= Number(params.minZoom))
|
||||
state.locationControl.map(l => l.zoom >= Number(params.minZoom))
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
return new LoginToggle(new Toggle(
|
||||
t.isClosed.SetClass("thanks"),
|
||||
closeButton,
|
||||
|
||||
|
||||
isClosed
|
||||
), t.loginToClose, state)
|
||||
}
|
||||
|
@ -180,7 +143,7 @@ class CloseNoteButton implements SpecialVisualization {
|
|||
|
||||
export default class SpecialVisualizations {
|
||||
|
||||
public static specialVisualizations : SpecialVisualization[] = SpecialVisualizations.init()
|
||||
public static specialVisualizations: SpecialVisualization[] = SpecialVisualizations.init()
|
||||
|
||||
public static HelpMessage() {
|
||||
|
||||
|
@ -207,28 +170,28 @@ export default class SpecialVisualizations {
|
|||
));
|
||||
|
||||
return new Combine([
|
||||
new Combine([
|
||||
|
||||
new Title("Special tag renderings", 1),
|
||||
|
||||
"In a tagrendering, some special values are substituted by an advanced UI-element. This allows advanced features and visualizations to be reused by custom themes or even to query third-party API's.",
|
||||
"General usage is `{func_name()}`, `{func_name(arg, someotherarg)}` or `{func_name(args):cssStyle}`. Note that you _do not_ need to use quotes around your arguments, the comma is enough to separate them. This also implies you cannot use a comma in your args",
|
||||
new Title("Using expanded syntax",4),
|
||||
`Instead of using \`{"render": {"en": "{some_special_visualisation(some_arg, some other really long message, more args)} , "nl": "{some_special_visualisation(some_arg, een boodschap in een andere taal, more args)}}, one can also write`,
|
||||
new FixedUiElement(JSON.stringify({
|
||||
render: {
|
||||
special:{
|
||||
type: "some_special_visualisation",
|
||||
"argname": "some_arg",
|
||||
"message":{
|
||||
en:"some other really long message",
|
||||
nl: "een boodschap in een andere taal"
|
||||
},
|
||||
"other_arg_name":"more args"
|
||||
new Combine([
|
||||
|
||||
new Title("Special tag renderings", 1),
|
||||
|
||||
"In a tagrendering, some special values are substituted by an advanced UI-element. This allows advanced features and visualizations to be reused by custom themes or even to query third-party API's.",
|
||||
"General usage is `{func_name()}`, `{func_name(arg, someotherarg)}` or `{func_name(args):cssStyle}`. Note that you _do not_ need to use quotes around your arguments, the comma is enough to separate them. This also implies you cannot use a comma in your args",
|
||||
new Title("Using expanded syntax", 4),
|
||||
`Instead of using \`{"render": {"en": "{some_special_visualisation(some_arg, some other really long message, more args)} , "nl": "{some_special_visualisation(some_arg, een boodschap in een andere taal, more args)}}, one can also write`,
|
||||
new FixedUiElement(JSON.stringify({
|
||||
render: {
|
||||
special: {
|
||||
type: "some_special_visualisation",
|
||||
"argname": "some_arg",
|
||||
"message": {
|
||||
en: "some other really long message",
|
||||
nl: "een boodschap in een andere taal"
|
||||
},
|
||||
"other_arg_name": "more args"
|
||||
}
|
||||
}
|
||||
}
|
||||
})).SetClass("code")
|
||||
]).SetClass("flex flex-col"),
|
||||
})).SetClass("code")
|
||||
]).SetClass("flex flex-col"),
|
||||
...helpTexts
|
||||
]
|
||||
).SetClass("flex flex-col");
|
||||
|
@ -297,6 +260,32 @@ export default class SpecialVisualizations {
|
|||
)
|
||||
|
||||
},
|
||||
{
|
||||
funcName: "wikidata_label",
|
||||
docs: "Shows the label of the corresponding wikidata-item",
|
||||
args: [
|
||||
{
|
||||
name: "keyToShowWikidataFor",
|
||||
doc: "Use the wikidata entry from this key to show the label",
|
||||
defaultValue: "wikidata"
|
||||
}
|
||||
],
|
||||
example: "`{wikidata_label()}` is a basic example, `{wikipedia(name:etymology:wikidata)}` to show the label itself",
|
||||
constr: (_, tagsSource, args) =>
|
||||
new VariableUiElement(
|
||||
tagsSource.map(tags => tags[args[0]])
|
||||
.map(wikidata => {
|
||||
wikidata = Utils.NoEmpty(wikidata?.split(";")?.map(wd => wd.trim()) ?? [])[0]
|
||||
const entry = Wikidata.LoadWikidataEntry(wikidata)
|
||||
return new VariableUiElement(entry.map(e => {
|
||||
if (e === undefined || e["success"] === undefined) {
|
||||
return wikidata
|
||||
}
|
||||
const response = <WikidataResponse>e["success"]
|
||||
return Translation.fromMap(response.labels)
|
||||
}))
|
||||
}))
|
||||
},
|
||||
{
|
||||
funcName: "minimap",
|
||||
docs: "A small map showing the selected feature.",
|
||||
|
@ -315,6 +304,9 @@ export default class SpecialVisualizations {
|
|||
example: "`{minimap()}`, `{minimap(17, id, _list_of_embedded_feature_ids_calculated_by_calculated_tag):height:10rem; border: 2px solid black}`",
|
||||
constr: (state, tagSource, args, _) => {
|
||||
|
||||
if(state === undefined){
|
||||
return undefined
|
||||
}
|
||||
const keys = [...args]
|
||||
keys.splice(0, 1)
|
||||
const featureStore = state.allElements.ContainingFeatures
|
||||
|
@ -482,7 +474,7 @@ export default class SpecialVisualizations {
|
|||
docs: "Downloads a JSON from the given URL, e.g. '{live(example.org/data.json, shorthand:x.y.z, other:a.b.c, shorthand)}' will download the given file, will create an object {shorthand: json[x][y][z], other: json[a][b][c] out of it and will return 'other' or 'json[a][b][c]. This is made to use in combination with tags, e.g. {live({url}, {url:format}, needed_value)}",
|
||||
example: "{live({url},{url:format},hour)} {live(https://data.mobility.brussels/bike/api/counts/?request=live&featureID=CB2105,hour:data.hour_cnt;day:data.day_cnt;year:data.year_cnt,hour)}",
|
||||
args: [{
|
||||
name: "Url",
|
||||
name: "Url",
|
||||
doc: "The URL to load",
|
||||
required: true
|
||||
}, {
|
||||
|
@ -623,7 +615,7 @@ export default class SpecialVisualizations {
|
|||
if (value === undefined) {
|
||||
return undefined
|
||||
}
|
||||
const allUnits = [].concat(...state.layoutToUse.layers.map(lyr => lyr.units))
|
||||
const allUnits = [].concat(...(state?.layoutToUse?.layers?.map(lyr => lyr.units) ?? []))
|
||||
const unit = allUnits.filter(unit => unit.isApplicableToKey(key))[0]
|
||||
if (unit === undefined) {
|
||||
return value;
|
||||
|
@ -783,7 +775,7 @@ export default class SpecialVisualizations {
|
|||
const textField = new TextField(
|
||||
{
|
||||
placeholder: t.addCommentPlaceholder,
|
||||
inputStyle: "width: 100%; height: 6rem;",
|
||||
inputStyle: "width: 100%; height: 6rem;",
|
||||
textAreaRows: 3,
|
||||
htmlType: "area"
|
||||
}
|
||||
|
@ -846,7 +838,7 @@ export default class SpecialVisualizations {
|
|||
textField,
|
||||
new Combine([
|
||||
stateButtons.SetClass("sm:mr-2"),
|
||||
new Toggle(addCommentButton,
|
||||
new Toggle(addCommentButton,
|
||||
new Combine([t.typeText]).SetClass("flex items-center h-full subtle"),
|
||||
textField.GetValue().map(t => t !== undefined && t.length >= 1)).SetClass("sm:mr-2")
|
||||
]).SetClass("sm:flex sm:justify-between sm:items-stretch")
|
||||
|
@ -947,7 +939,7 @@ export default class SpecialVisualizations {
|
|||
]
|
||||
|
||||
specialVisualizations.push(new AutoApplyButton(specialVisualizations))
|
||||
|
||||
|
||||
return specialVisualizations;
|
||||
}
|
||||
|
||||
|
|
|
@ -54,7 +54,7 @@ export class SubstitutedTranslation extends VariableUiElement {
|
|||
}
|
||||
const viz = proto.special;
|
||||
try {
|
||||
return viz.func.constr(state, tagsSource, proto.special.args, DefaultGuiState.state).SetStyle(proto.special.style);
|
||||
return viz.func.constr(state, tagsSource, proto.special.args, DefaultGuiState.state)?.SetStyle(proto.special.style);
|
||||
} catch (e) {
|
||||
console.error("SPECIALRENDERING FAILED for", tagsSource.data?.id, e)
|
||||
return new FixedUiElement(`Could not generate special rendering for ${viz.func.funcName}(${viz.args.join(", ")}) ${e}`).SetStyle("alert")
|
||||
|
@ -80,7 +80,7 @@ export class SubstitutedTranslation extends VariableUiElement {
|
|||
}
|
||||
}[] {
|
||||
|
||||
for (const knownSpecial of SpecialVisualizations.specialVisualizations.concat(extraMappings)) {
|
||||
for (const knownSpecial of extraMappings.concat(SpecialVisualizations.specialVisualizations)) {
|
||||
|
||||
// Note: the '.*?' in the regex reads as 'any character, but in a non-greedy way'
|
||||
const matched = template.match(`(.*){${knownSpecial.funcName}\\((.*?)\\)(:.*)?}(.*)`);
|
||||
|
|
|
@ -17,14 +17,20 @@ export default class WikidataSearchBox extends InputElement<string> {
|
|||
IsSelected: UIEventSource<boolean> = new UIEventSource<boolean>(false);
|
||||
private readonly wikidataId: UIEventSource<string>
|
||||
private readonly searchText: UIEventSource<string>
|
||||
private readonly instanceOf?: number[];
|
||||
private readonly notInstanceOf?: number[];
|
||||
|
||||
constructor(options?: {
|
||||
searchText?: UIEventSource<string>,
|
||||
value?: UIEventSource<string>
|
||||
value?: UIEventSource<string>,
|
||||
notInstanceOf?: number[],
|
||||
instanceOf?: number[]
|
||||
}) {
|
||||
super();
|
||||
this.searchText = options?.searchText
|
||||
this.wikidataId = options?.value ?? new UIEventSource<string>(undefined);
|
||||
this.instanceOf = options?.instanceOf
|
||||
this.notInstanceOf = options?.notInstanceOf
|
||||
}
|
||||
|
||||
GetValue(): UIEventSource<string> {
|
||||
|
@ -59,7 +65,9 @@ export default class WikidataSearchBox extends InputElement<string> {
|
|||
if (promise === undefined) {
|
||||
promise = Wikidata.searchAndFetch(searchText, {
|
||||
lang,
|
||||
maxCount: 5
|
||||
maxCount: 5,
|
||||
notInstanceOf: this.notInstanceOf,
|
||||
instanceOf: this.instanceOf
|
||||
}
|
||||
)
|
||||
WikidataSearchBox._searchCache.set(key, promise)
|
||||
|
@ -75,13 +83,15 @@ export default class WikidataSearchBox extends InputElement<string> {
|
|||
return new Combine([Translations.t.general.wikipedia.failed.Clone().SetClass("alert"), searchFailMessage.data])
|
||||
}
|
||||
|
||||
if (searchField.GetValue().data.length === 0) {
|
||||
return Translations.t.general.wikipedia.doSearch
|
||||
}
|
||||
|
||||
if (searchResults.length === 0) {
|
||||
return Translations.t.general.wikipedia.noResults.Subs({search: searchField.GetValue().data ?? ""})
|
||||
}
|
||||
|
||||
if (searchResults.length === 0) {
|
||||
return Translations.t.general.wikipedia.doSearch
|
||||
}
|
||||
|
||||
|
||||
return new Combine(searchResults.map(wikidataresponse => {
|
||||
const el = WikidataPreviewBox.WikidataResponsePreview(wikidataresponse).SetClass("rounded-xl p-1 sm:p-2 md:p-3 m-px border-2 sm:border-4 transition-colors")
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue