repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
rill-flow | github_2023 | weibocom | typescript | VAxios.configAxios | configAxios(config: CreateAxiosOptions) {
if (!this.axiosInstance) {
return;
}
this.createAxios(config);
} | /**
* @description: Reconfigure axios
*/ | https://github.com/weibocom/rill-flow/blob/287042161999be39b1b92968f8fd60b3825b7fb1/rill-flow-ui/src/utils/http/axios/Axios.ts#L52-L57 | 287042161999be39b1b92968f8fd60b3825b7fb1 |
rill-flow | github_2023 | weibocom | typescript | VAxios.setHeader | setHeader(headers: any): void {
if (!this.axiosInstance) {
return;
}
Object.assign(this.axiosInstance.defaults.headers, headers);
} | /**
* @description: Set general header
*/ | https://github.com/weibocom/rill-flow/blob/287042161999be39b1b92968f8fd60b3825b7fb1/rill-flow-ui/src/utils/http/axios/Axios.ts#L62-L67 | 287042161999be39b1b92968f8fd60b3825b7fb1 |
rill-flow | github_2023 | weibocom | typescript | VAxios.setupInterceptors | private setupInterceptors() {
// const transform = this.getTransform();
const {
axiosInstance,
options: { transform },
} = this;
if (!transform) {
return;
}
const {
requestInterceptors,
requestInterceptorsCatch,
responseInterceptors,
responseInterceptorsCatch,
} = transform;
const axiosCanceler = new AxiosCanceler();
// Request interceptor configuration processing
this.axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
// If cancel repeat request is turned on, then cancel repeat request is prohibited
const { requestOptions } = this.options;
const ignoreCancelToken = requestOptions?.ignoreCancelToken ?? true;
!ignoreCancelToken && axiosCanceler.addPending(config);
if (requestInterceptors && isFunction(requestInterceptors)) {
config = requestInterceptors(config, this.options);
}
return config;
}, undefined);
// Request interceptor error capture
requestInterceptorsCatch &&
isFunction(requestInterceptorsCatch) &&
this.axiosInstance.interceptors.request.use(undefined, requestInterceptorsCatch);
// Response result interceptor processing
this.axiosInstance.interceptors.response.use((res: AxiosResponse<any>) => {
res && axiosCanceler.removePending(res.config);
if (responseInterceptors && isFunction(responseInterceptors)) {
res = responseInterceptors(res);
}
return res;
}, undefined);
// Response result interceptor error capture
responseInterceptorsCatch &&
isFunction(responseInterceptorsCatch) &&
this.axiosInstance.interceptors.response.use(undefined, (error) => {
return responseInterceptorsCatch(axiosInstance, error);
});
} | /**
* @description: Interceptor configuration 拦截器配置
*/ | https://github.com/weibocom/rill-flow/blob/287042161999be39b1b92968f8fd60b3825b7fb1/rill-flow-ui/src/utils/http/axios/Axios.ts#L72-L124 | 287042161999be39b1b92968f8fd60b3825b7fb1 |
rill-flow | github_2023 | weibocom | typescript | VAxios.uploadFile | uploadFile<T = any>(config: AxiosRequestConfig, params: UploadFileParams) {
const formData = new window.FormData();
const customFilename = params.name || 'file';
if (params.filename) {
formData.append(customFilename, params.file, params.filename);
} else {
formData.append(customFilename, params.file);
}
if (params.data) {
Object.keys(params.data).forEach((key) => {
const value = params.data![key];
if (Array.isArray(value)) {
value.forEach((item) => {
formData.append(`${key}[]`, item);
});
return;
}
formData.append(key, params.data![key]);
});
}
return this.axiosInstance.request<T>({
...config,
method: 'POST',
data: formData,
headers: {
'Content-type': ContentTypeEnum.FORM_DATA,
// @ts-ignore
ignoreCancelToken: true,
},
});
} | /**
* @description: File Upload
*/ | https://github.com/weibocom/rill-flow/blob/287042161999be39b1b92968f8fd60b3825b7fb1/rill-flow-ui/src/utils/http/axios/Axios.ts#L129-L163 | 287042161999be39b1b92968f8fd60b3825b7fb1 |
rill-flow | github_2023 | weibocom | typescript | VAxios.supportFormData | supportFormData(config: AxiosRequestConfig) {
const headers = config.headers || this.options.headers;
const contentType = headers?.['Content-Type'] || headers?.['content-type'];
if (
contentType !== ContentTypeEnum.FORM_URLENCODED ||
!Reflect.has(config, 'data') ||
config.method?.toUpperCase() === RequestEnum.GET
) {
return config;
}
return {
...config,
data: qs.stringify(config.data, { arrayFormat: 'brackets' }),
};
} | // support form-data | https://github.com/weibocom/rill-flow/blob/287042161999be39b1b92968f8fd60b3825b7fb1/rill-flow-ui/src/utils/http/axios/Axios.ts#L166-L182 | 287042161999be39b1b92968f8fd60b3825b7fb1 |
rill-flow | github_2023 | weibocom | typescript | AxiosCanceler.addPending | public addPending(config: AxiosRequestConfig): void {
this.removePending(config);
const url = getPendingUrl(config);
const controller = new AbortController();
config.signal = config.signal || controller.signal;
if (!pendingMap.has(url)) {
// 如果当前请求不在等待中,将其添加到等待中
pendingMap.set(url, controller);
}
} | /**
* 添加请求
* @param config 请求配置
*/ | https://github.com/weibocom/rill-flow/blob/287042161999be39b1b92968f8fd60b3825b7fb1/rill-flow-ui/src/utils/http/axios/axiosCancel.ts#L15-L24 | 287042161999be39b1b92968f8fd60b3825b7fb1 |
rill-flow | github_2023 | weibocom | typescript | AxiosCanceler.removeAllPending | public removeAllPending(): void {
pendingMap.forEach((abortController) => {
if (abortController) {
abortController.abort();
}
});
this.reset();
} | /**
* 清除所有等待中的请求
*/ | https://github.com/weibocom/rill-flow/blob/287042161999be39b1b92968f8fd60b3825b7fb1/rill-flow-ui/src/utils/http/axios/axiosCancel.ts#L29-L36 | 287042161999be39b1b92968f8fd60b3825b7fb1 |
rill-flow | github_2023 | weibocom | typescript | AxiosCanceler.removePending | public removePending(config: AxiosRequestConfig): void {
const url = getPendingUrl(config);
if (pendingMap.has(url)) {
// 如果当前请求在等待中,取消它并将其从等待中移除
const abortController = pendingMap.get(url);
if (abortController) {
abortController.abort(url);
}
pendingMap.delete(url);
}
} | /**
* 移除请求
* @param config 请求配置
*/ | https://github.com/weibocom/rill-flow/blob/287042161999be39b1b92968f8fd60b3825b7fb1/rill-flow-ui/src/utils/http/axios/axiosCancel.ts#L42-L52 | 287042161999be39b1b92968f8fd60b3825b7fb1 |
rill-flow | github_2023 | weibocom | typescript | AxiosCanceler.reset | public reset(): void {
pendingMap.clear();
} | /**
* 重置
*/ | https://github.com/weibocom/rill-flow/blob/287042161999be39b1b92968f8fd60b3825b7fb1/rill-flow-ui/src/utils/http/axios/axiosCancel.ts#L57-L59 | 287042161999be39b1b92968f8fd60b3825b7fb1 |
rill-flow | github_2023 | weibocom | typescript | AxiosRetry.retry | retry(axiosInstance: AxiosInstance, error: AxiosError) {
// @ts-ignore
const { config } = error.response;
const { waitTime, count } = config?.requestOptions?.retryRequest ?? {};
config.__retryCount = config.__retryCount || 0;
if (config.__retryCount >= count) {
return Promise.reject(error);
}
config.__retryCount += 1;
//请求返回后config的header不正确造成重试请求失败,删除返回headers采用默认headers
delete config.headers;
return this.delay(waitTime).then(() => axiosInstance(config));
} | /**
* 重试
*/ | https://github.com/weibocom/rill-flow/blob/287042161999be39b1b92968f8fd60b3825b7fb1/rill-flow-ui/src/utils/http/axios/axiosRetry.ts#L10-L22 | 287042161999be39b1b92968f8fd60b3825b7fb1 |
rill-flow | github_2023 | weibocom | typescript | AxiosRetry.delay | private delay(waitTime: number) {
return new Promise((resolve) => setTimeout(resolve, waitTime));
} | /**
* 延迟
*/ | https://github.com/weibocom/rill-flow/blob/287042161999be39b1b92968f8fd60b3825b7fb1/rill-flow-ui/src/utils/http/axios/axiosRetry.ts#L27-L29 | 287042161999be39b1b92968f8fd60b3825b7fb1 |
zerostep | github_2023 | zerostep-ai | typescript | sendTaskStartMessage | const sendTaskStartMessage = async (page: Page, task: string, taskId: string, options?: StepOptions) => {
const snapshot = await playwright.getSnapshot(page)
const message: TaskStartZeroStepMessage = {
type: 'task-start',
packageVersion: meta.getVersion(),
taskId,
task,
snapshot,
options,
}
await webSocket.sendWebSocketMessage(message)
} | /**
* Sends a message over the websocket to begin an AI task.
*/ | https://github.com/zerostep-ai/zerostep/blob/7c813beafa09f46bdd8c98b826d2085c936443c9/packages/playwright/src/index.ts#L104-L116 | 7c813beafa09f46bdd8c98b826d2085c936443c9 |
zerostep | github_2023 | zerostep-ai | typescript | sendCommandResolveMessage | const sendCommandResolveMessage = async (index: number, taskId: string, result: any) => {
const message: CommandResponseZeroStepMessage = {
type: 'command-response',
packageVersion: meta.getVersion(),
taskId,
index,
result: result === undefined || result === null ? "null" : JSON.stringify(result),
}
await webSocket.sendWebSocketMessage(message)
} | /**
* Sends a message over the websocket in response to an AI command completing.
*/ | https://github.com/zerostep-ai/zerostep/blob/7c813beafa09f46bdd8c98b826d2085c936443c9/packages/playwright/src/index.ts#L121-L131 | 7c813beafa09f46bdd8c98b826d2085c936443c9 |
zerostep | github_2023 | zerostep-ai | typescript | runCommandsToCompletion | const runCommandsToCompletion = async (page: Page, test: TestType<any, any>, taskId: string) => {
return new Promise<TaskCompleteZeroStepMessage>((resolve) => {
webSocket.addWebSocketMessageHandler(taskId, (data, removeListener) => {
// Only respond to messages corresponding to the task for which this
// listener was bound.
if (!data.taskId || data.taskId === taskId) {
switch (data.type) {
case 'command-request':
const prettyCommandName = getPrettyCommandName(data.name)
test.step(`${PACKAGE_NAME}.action ${prettyCommandName}`, async () => {
const result = await executeCommand(page, data)
await sendCommandResolveMessage(data.index, taskId, result)
})
break
case 'task-complete':
removeListener()
// If there was a response in the completion, print it as
// a test step in the actions list.
if (data.result?.assertion !== undefined) {
test.step(`${PACKAGE_NAME}.assertion ${data.result.assertion}`, async () => {
resolve(data)
})
} else if (data.result?.query !== undefined) {
test.step(`${PACKAGE_NAME}.response ${data.result.query}`, async () => {
resolve(data)
})
} else {
resolve(data)
}
break
}
}
})
})
} | /**
* Listens for websocket commands, executes them, then responds in a promise that
* is resolved once we see the task-complete message.
*/ | https://github.com/zerostep-ai/zerostep/blob/7c813beafa09f46bdd8c98b826d2085c936443c9/packages/playwright/src/index.ts#L137-L171 | 7c813beafa09f46bdd8c98b826d2085c936443c9 |
zerostep | github_2023 | zerostep-ai | typescript | executeCommand | const executeCommand = async (page: Page, command: CommandRequestZeroStepMessage): Promise<any> => {
switch (command.name) {
// CDP
case 'getDOMSnapshot':
return await cdp.getDOMSnapshot(page)
case 'executeScript':
return await cdp.executeScript(page, command.arguments as { script: string, args: any[] })
case 'getCurrentUrl':
return await cdp.getCurrentUrl(page)
case 'findElements':
return await cdp.findElements(page, command.arguments as { using: string, value: string })
case 'getElementTagName':
return await cdp.getElementTagName(page, command.arguments as { id: string })
case 'getElementRect':
return await cdp.getElementRect(page, command.arguments as { id: string })
case 'getElementAttribute':
return await cdp.getElementAttribute(page, command.arguments as { id: string, name: string })
case 'clearElement':
return await cdp.clearElement(page, command.arguments as { id: string })
case 'get':
return await cdp.get(page, command.arguments as { url: string })
case 'getTitle':
return await cdp.getTitle(page)
case 'scrollIntoView':
return await cdp.scrollIntoView(page, command.arguments as { id: string })
case 'currentUrl':
return await cdp.getCurrentUrl(page)
// Queries
case 'snapshot':
return await playwright.getSnapshot(page)
// Actions using CDP Element
case 'clickElement':
return await playwright.clickCDPElement(page, command.arguments as { id: string })
case 'sendKeysToElement':
return await playwright.clickAndInputCDPElement(page, command.arguments as { id: string, value: string })
case 'hoverElement':
return await playwright.hoverCDPElement(page, command.arguments as { id: string })
case 'scrollElement':
return await cdp.scrollElement(page, command.arguments as { id: string, target: ScrollType })
// Actions using Location
case 'clickLocation':
return await playwright.clickLocation(page, command.arguments as { x: number, y: number })
case 'hoverLocation':
return await playwright.hoverLocation(page, command.arguments as { x: number, y: number })
case 'clickAndInputLocation':
return await playwright.clickAndInputLocation(page, command.arguments as { x: number, y: number, value: string })
case 'getElementAtLocation':
return await playwright.getElementAtLocation(page, command.arguments as { x: number, y: number })
// Actions using Device
case 'sendKeys':
return await playwright.input(page, command.arguments as { value: string })
case 'keypressEnter':
return await playwright.keypressEnter(page)
case 'navigate':
return await playwright.navigate(page, command.arguments as { url: string })
// Actions using Script
case 'scrollPage':
return await playwright.scrollPageScript(page, command.arguments as { target: ScrollType })
default:
throw Error(`Unsupported command ${command.name}`)
}
} | /**
* Executes a webdriver command passed over the websocket using CDP.
*/ | https://github.com/zerostep-ai/zerostep/blob/7c813beafa09f46bdd8c98b826d2085c936443c9/packages/playwright/src/index.ts#L176-L243 | 7c813beafa09f46bdd8c98b826d2085c936443c9 |
zerostep | github_2023 | zerostep-ai | typescript | runInParallel | const runInParallel: typeof ai = async (tasks, config, options) => {
if (!Array.isArray(tasks) || tasks.length === 0) {
Promise.reject('Empty task list, nothing to do')
}
const parallelism = options?.parallelism || 10
const failImmediately = options?.failImmediately || false
const tasksArray = tasks as string[]
const allValues: any[] = []
for (let i = 0; i < tasksArray.length; i += parallelism) {
const taskPromises = tasksArray.slice(i, i + parallelism).map(_ => ai(_, config, options))
if (failImmediately) {
const values = await Promise.all(taskPromises)
for (let i = 0; i < values.length; i++) {
const value = values[i]
allValues.push(value)
}
} else {
const results = await Promise.allSettled(taskPromises)
for (let i = 0; i < results.length; i++) {
const result = results[i]
allValues.push(result.status === 'fulfilled' ? result.value : result)
}
}
}
return allValues
} | /**
* Runs the provided tasks in parallel by chunking them up according to the
* `parallelism` option and waiting for all chunks to complete.
*/ | https://github.com/zerostep-ai/zerostep/blob/7c813beafa09f46bdd8c98b826d2085c936443c9/packages/playwright/src/index.ts#L249-L278 | 7c813beafa09f46bdd8c98b826d2085c936443c9 |
ollama-logseq | github_2023 | omagdy7 | typescript | css | const css = (t, ...args) => String.raw(t, ...args); | // @ts-expect-error | https://github.com/omagdy7/ollama-logseq/blob/cfd6f171e716f3f0f5976e96272d084db8dd0dec/src/main.tsx#L13-L13 | cfd6f171e716f3f0f5976e96272d084db8dd0dec |
ollama-logseq | github_2023 | omagdy7 | typescript | getIndentLevel | function getIndentLevel(line: string): number {
const firstCharIndex = line.search(/\S/);
// no non-whitespace => treat as top-level
if (firstCharIndex < 0) {
return 0;
}
// e.g. baseIndent=2 → each 2 leading spaces => +1 nesting level
const baseIndent = 3;
return Math.floor(firstCharIndex / baseIndent);
} | // Helper: Determine indent-based nesting level. | https://github.com/omagdy7/ollama-logseq/blob/cfd6f171e716f3f0f5976e96272d084db8dd0dec/src/ollama.tsx#L351-L360 | cfd6f171e716f3f0f5976e96272d084db8dd0dec |
ArisuAutoSweeper | github_2023 | TheFunny | typescript | getAlasABSPath | const getAlasABSPath = (
files: string[] = ['**/config/deploy.yaml', '**/config/deploy.template.yaml'],
rootName: string | string[] = ['AzurLaneAutoScript', 'Alas', 'ArisuAutoSweeper'],
) => {
const path = require('path');
const sep = path.sep;
const fg = require('fast-glob');
let appAbsPath = process.cwd();
if (isMacintosh && import.meta.env.PROD) {
appAbsPath = app?.getAppPath() || process.execPath;
}
while (fs.lstatSync(appAbsPath).isFile()) {
appAbsPath = appAbsPath.split(sep).slice(0, -1).join(sep);
}
let alasABSPath = '';
let hasRootName = false;
if (typeof rootName === 'string') {
hasRootName = appAbsPath.includes(rootName);
} else if (Array.isArray(rootName)) {
hasRootName = rootName.some(item =>
appAbsPath.toLocaleLowerCase().includes(item.toLocaleLowerCase()),
);
}
if (hasRootName) {
const appAbsPathArr = appAbsPath.split(sep);
let flag = false;
while (hasRootName && !flag) {
const entries = fg.sync(files, {
dot: true,
cwd: appAbsPathArr.join(sep) as string,
});
if (entries.length > 0) {
flag = true;
alasABSPath = appAbsPathArr.join(sep);
}
appAbsPathArr.pop();
}
} else {
let step = 4;
const appAbsPathArr = appAbsPath.split(sep);
let flag = false;
while (step > 0 && !flag) {
appAbsPathArr.pop();
const entries = fg.sync(files, {
dot: true,
cwd: appAbsPathArr.join(sep) as string,
});
if (entries.length > 0) {
flag = true;
alasABSPath = appAbsPathArr.join(sep);
}
step--;
}
}
return alasABSPath.endsWith(sep) ? alasABSPath : alasABSPath + sep;
}; | /**
* Get the absolute path of the project root directory
* @param files
* @param rootName
*/ | https://github.com/TheFunny/ArisuAutoSweeper/blob/62c147fdab131583c259a5dcdec0b80e27aff299/webapp/packages/common/utils/getAlasABSPath.ts#L9-L70 | 62c147fdab131583c259a5dcdec0b80e27aff299 |
ArisuAutoSweeper | github_2023 | TheFunny | typescript | changeLocale | async function changeLocale(locale: LocaleType) {
const globalI18n = i18n.global;
const currentLocale = unref(globalI18n.locale);
if (currentLocale === locale) {
return locale;
}
const langModule = messages[locale];
if (!langModule) return;
globalI18n.setLocaleMessage(locale, langModule);
setI18nLanguage(locale);
return locale;
} | // Switching the language will change the locale of useI18n | https://github.com/TheFunny/ArisuAutoSweeper/blob/62c147fdab131583c259a5dcdec0b80e27aff299/webapp/packages/renderer/src/locales/useLocale.ts#L30-L43 | 62c147fdab131583c259a5dcdec0b80e27aff299 |
ArisuAutoSweeper | github_2023 | TheFunny | typescript | formatComponentName | function formatComponentName(vm: any) {
if (vm.$root === vm) {
return {
name: 'root',
path: 'root',
};
}
const options = vm.$options as any;
if (!options) {
return {
name: 'anonymous',
path: 'anonymous',
};
}
const name = options.name || options._componentTag;
return {
name: name,
path: options.__file,
};
} | /**
* get comp name
* @param vm
*/ | https://github.com/TheFunny/ArisuAutoSweeper/blob/62c147fdab131583c259a5dcdec0b80e27aff299/webapp/packages/renderer/src/logics/error-handle/index.ts#L16-L36 | 62c147fdab131583c259a5dcdec0b80e27aff299 |
ArisuAutoSweeper | github_2023 | TheFunny | typescript | processStackMsg | function processStackMsg(error: Error) {
if (!error.stack) {
return '';
}
let stack = error.stack
.replace(/\n/gi, '') // Remove line breaks to save the size of the transmitted content
.replace(/\bat\b/gi, '@') // At in chrome, @ in ff
.split('@') // Split information with @
.slice(0, 9) // The maximum stack length (Error.stackTraceLimit = 10), so only take the first 10
.map(v => v.replace(/^\s*|\s*$/g, '')) // Remove extra spaces
.join('~') // Manually add separators for later display
.replace(/\?[^:]+/gi, ''); // Remove redundant parameters of js file links (?x=1 and the like)
const msg = error.toString();
if (stack.indexOf(msg) < 0) {
stack = msg + '@' + stack;
}
return stack;
} | /**
* Handling error stack information
* @param error
*/ | https://github.com/TheFunny/ArisuAutoSweeper/blob/62c147fdab131583c259a5dcdec0b80e27aff299/webapp/packages/renderer/src/logics/error-handle/index.ts#L72-L89 | 62c147fdab131583c259a5dcdec0b80e27aff299 |
aws-cdk-stack-builder-tool | github_2023 | aws-samples | typescript | TypeScriptGenerator.importName | importName(fqn: string) {
const importName = fqn
.replaceAll(".", "/")
.split("/")
.slice(0, -1)
.join("/")
.replaceAll("_", "-");
return importName;
} | // @aws-cdk_aws/batch-alpha | https://github.com/aws-samples/aws-cdk-stack-builder-tool/blob/fb243b1bd75f908bad10c7a1d2faed009510f7ed/src/react-app/src/targets/typescript/typescript-generator.ts#L677-L686 | fb243b1bd75f908bad10c7a1d2faed009510f7ed |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onAutofillButtonClick | const onAutofillButtonClick = ({ target }: Event): void => {
const dataset = (target as HTMLButtonElement).dataset
console.debug("onAutofillButtonClick", dataset)
;(loginForm.elements.namedItem("display_name_or_email") as HTMLInputElement).value = dataset.login
loginForm.querySelector("input[type=password][data-name=password]").value = dataset.password
;(loginForm.elements.namedItem("remember") as HTMLInputElement).checked = true
loginForm.requestSubmit()
} | // Autofill buttons are present in development environment | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_login.ts#L30-L37 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | roundPy2 | const roundPy2 = (value: number): number => (value + (value < 0 ? -0.5 : 0.5)) | 0 | // Encoded Polyline Algorithm Format | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_polyline.ts#L10-L10 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | getObjectRequestUrl | const getObjectRequestUrl = (object: OSMObject): string => {
const type = object.type === "note" ? "notes" : object.type
// When requested for complex object, request for full version (incl. object's members)
// Ignore version specification as there is a very high chance it will be rendered incorrectly
if (type === "way" || type === "relation") {
return `${config.apiUrl}/api/0.6/${type}/${object.id}/full`
}
// @ts-ignore
const version = object.version
return version
? `${config.apiUrl}/api/0.6/${type}/${object.id}/${version}`
: `${config.apiUrl}/api/0.6/${type}/${object.id}`
} | /**
* Get object request URL
* @example
* getObjectRequestUrl({ type: "node", id: 123456 })
* // => "https://api.openstreetmap.org/api/0.6/node/123456"
*/ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_remote-edit.ts#L15-L29 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | getBoundsFromCoords | const getBoundsFromCoords = ({ lon, lat, zoom }: LonLatZoom, paddingRatio = 0): Bounds => {
// Assume the map takes up the entire screen
const mapHeight = window.innerHeight
const mapWidth = window.innerWidth
const tileSize = 256
const tileCountHalfX = mapWidth / tileSize / 2
const tileCountHalfY = mapHeight / tileSize / 2
const n = 2 ** zoom
const deltaLon = (tileCountHalfX / n) * 360 * (1 + paddingRatio)
const deltaLat = (tileCountHalfY / n) * 180 * (1 + paddingRatio)
return [lon - deltaLon, lat - deltaLat, lon + deltaLon, lat + deltaLat]
} | /** Get bounds from coordinates and zoom level */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_remote-edit.ts#L32-L46 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | abortRequest | const abortRequest = (source: Element, newController: boolean): AbortController | null => {
const controller = abortControllers.get(source)
controller?.abort()
// When a new controller is requested, replace the old one and return it
if (newController) {
const controller = new AbortController()
abortControllers.set(source, controller)
return controller
}
// Otherwise, delete the controller and return null
abortControllers.delete(source)
return null
} | /** Abort any pending request for the given source element, optionally returning a new AbortController */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_rich-text.ts#L6-L20 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onEditClick | const onEditClick = () => {
abortRequest(sourceTextArea, false)
for (const button of editButtons) button.disabled = true
for (const button of previewButtons) button.disabled = false
for (const button of helpButtons) button.disabled = false
sourceTextArea.classList.remove("d-none")
previewDiv.classList.add("d-none")
previewDiv.innerHTML = ""
helpDiv.classList.add("d-none")
} | /** On edit button click, abort any requests and show the source textarea */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_rich-text.ts#L30-L41 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onPreviewClick | const onPreviewClick = () => {
const abortController = abortRequest(sourceTextArea, true)
for (const button of editButtons) button.disabled = false
for (const button of previewButtons) button.disabled = true
for (const button of helpButtons) button.disabled = false
sourceTextArea.classList.add("d-none")
previewDiv.classList.remove("d-none")
previewDiv.innerHTML = i18next.t("browse.start_rjs.loading")
helpDiv.classList.add("d-none")
const formData = new FormData()
formData.append("text", sourceTextArea.value)
fetch("/api/web/rich-text", {
method: "POST",
body: formData,
mode: "same-origin",
cache: "no-store",
signal: abortController.signal,
priority: "high",
})
.then(async (resp) => {
previewDiv.innerHTML = await resp.text()
})
.catch((error) => {
if (error.name === "AbortError") return
console.error("Failed to fetch rich text preview", error)
previewDiv.innerHTML = error.message
// TODO: standard alert
})
} | /** On preview button click, abort any requests and fetch the preview */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_rich-text.ts#L46-L78 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onHelpClick | const onHelpClick = () => {
abortRequest(sourceTextArea, false)
for (const button of editButtons) button.disabled = false
for (const button of previewButtons) button.disabled = false
for (const button of helpButtons) button.disabled = true
sourceTextArea.classList.add("d-none")
previewDiv.classList.add("d-none")
previewDiv.innerHTML = ""
helpDiv.classList.remove("d-none")
} | /** On help button click, show the help content */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_rich-text.ts#L83-L94 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | handleElementFeedback | const handleElementFeedback = (
element: HTMLInputElement,
type: "success" | "info" | "error",
message: string,
): void => {
if (element.classList.contains("hidden-password-input")) {
const actualElement = form.querySelector(`input[type=password][data-name="${element.name}"]`)
if (actualElement) {
console.debug("Redirecting element feedback for", element.name)
handleElementFeedback(actualElement, type, message)
return
}
}
element.parentElement.classList.add("position-relative")
let feedback = element.nextElementSibling
if (!feedback?.classList.contains("element-feedback")) {
feedback = document.createElement("div")
feedback.classList.add("element-feedback")
element.after(feedback)
}
if (type === "success" || type === "info") {
feedback.classList.add("valid-tooltip")
feedback.classList.remove("invalid-tooltip")
element.classList.add("is-valid")
element.classList.remove("is-invalid")
} else {
feedback.classList.add("invalid-tooltip")
feedback.classList.remove("valid-tooltip")
element.classList.add("is-invalid")
element.classList.remove("is-valid")
}
feedback.textContent = message
// Remove feedback on change or submit
const onInput = () => {
if (!feedback) return
console.debug("Invalidating form feedback")
form.dispatchEvent(new CustomEvent("invalidate"))
}
const onInvalidated = () => {
if (!feedback) return
console.debug("configureStandardForm", "handleElementFeedback", "onInvalidated")
feedback.remove()
feedback = null
element.classList.remove("is-valid", "is-invalid")
}
// Listen for events that invalidate the feedback
element.addEventListener("input", onInput, { once: true })
form.addEventListener("invalidate", onInvalidated, { once: true })
form.addEventListener("submit", onInvalidated, { once: true })
} | /** Handle feedback for a specific element */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_standard-form.ts#L48-L104 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onInput | const onInput = () => {
if (!feedback) return
console.debug("Invalidating form feedback")
form.dispatchEvent(new CustomEvent("invalidate"))
} | // Remove feedback on change or submit | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_standard-form.ts#L86-L90 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | handleFormFeedback | const handleFormFeedback = (type: "success" | "info" | "error", message: string): void => {
let feedback = form.querySelector(".form-feedback")
let feedbackAlert: Alert | null = null
if (!feedback) {
feedback = document.createElement("div")
feedback.classList.add("form-feedback", "alert", "alert-dismissible", "fade", "show")
feedback.role = "alert"
const span = document.createElement("span")
feedback.append(span)
const closeButton = document.createElement("button")
closeButton.type = "button"
closeButton.classList.add("btn-close")
closeButton.ariaLabel = i18next.t("javascripts.close")
closeButton.dataset.bsDismiss = "alert"
feedback.append(closeButton)
feedbackAlert = new Alert(feedback)
if (options?.formAppend) {
feedback.classList.add("alert-last")
form.append(feedback)
} else {
form.prepend(feedback)
}
}
if (type === "success") {
feedback.classList.remove("alert-info", "alert-danger")
feedback.classList.add("alert-success")
} else if (type === "info") {
feedback.classList.remove("alert-success", "alert-danger")
feedback.classList.add("alert-info")
} else {
feedback.classList.remove("alert-success", "alert-info")
feedback.classList.add("alert-danger")
}
feedback.firstElementChild.textContent = message
// Remove feedback on submit
const onInvalidated = () => {
if (!feedback) return
console.debug("configureStandardForm", "handleFormFeedback", "onInvalidated")
feedbackAlert.dispose()
feedbackAlert = null
feedback.remove()
feedback = null
}
// Listen for events that invalidate the feedback
form.addEventListener("invalidate", onInvalidated, { once: true })
form.addEventListener("submit", onInvalidated, { once: true })
} | /** Handle feedback for the entire form */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_standard-form.ts#L107-L158 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onInvalidated | const onInvalidated = () => {
if (!feedback) return
console.debug("configureStandardForm", "handleFormFeedback", "onInvalidated")
feedbackAlert.dispose()
feedbackAlert = null
feedback.remove()
feedback = null
} | // Remove feedback on submit | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_standard-form.ts#L146-L153 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | loadSystemApp | const loadSystemApp = (clientId: string, successCallback: (token: string) => void): void => {
console.debug("loadSystemApp", clientId)
const accessToken = getSystemAppAccessToken(clientId)
if (!accessToken) {
createAccessToken(clientId, successCallback)
return
}
fetch("/api/0.6/user/details", {
method: "GET",
credentials: "omit",
headers: { authorization: `Bearer ${accessToken}` },
mode: "same-origin",
cache: "no-store",
priority: "high",
})
.then((resp) => {
if (!resp.ok) throw new Error(`${resp.status} ${resp.statusText}`)
console.debug("Using cached system app access token")
successCallback(accessToken)
})
.catch(() => {
console.debug("Cached system app access token is invalid")
createAccessToken(clientId, successCallback)
})
} | /** Load system app access token and call successCallback with it */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_system-app.ts#L5-L31 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | generatePathData | const generatePathData = (coords: [number, number][]): string => {
const ds = [`M${coords[0][0]},${coords[0][1]}`]
for (const pair of coords.slice(1)) ds.push(`L${pair[0]},${pair[1]}`)
return ds.join(" ")
} | /** Generate a path data string from coordinates in [x, y] pairs */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_trace-svg.ts#L54-L58 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onMapClick | const onMapClick = ({ latlng }: { latlng: L.LatLng }) => {
const precision = zoomPrecision(map.getZoom())
const lon = latlng.lng.toFixed(precision)
const lat = latlng.lat.toFixed(precision)
const latLng = L.latLng(Number(lat), Number(lon))
lonInput.value = lon
latInput.value = lat
// If there's already a marker, move it, otherwise create a new one
if (marker) marker.setLatLng(latLng)
else marker = markerFactory(latLng)
} | /** On map click, update the coordinates and move the marker */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_user-settings-home.ts#L55-L67 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onGeolocationSuccess | const onGeolocationSuccess = (position: GeolocationPosition) => {
console.debug("onGeolocationSuccess", position)
const lon = position.coords.longitude
const lat = position.coords.latitude
const zoom = 17
const geolocationState: MapState = { lon, lat, zoom, layersCode: params.layers }
let startHref = "/edit"
if (Object.keys(startParams).length) startHref += `?${qsEncode(startParams)}`
startHref += encodeMapState(geolocationState)
startButton.href = startHref
startButton.removeEventListener("click", onStartButtonClick)
} | // If location was not provided, request navigator.geolocation | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_welcome.ts#L40-L52 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onGeolocationFailure | const onGeolocationFailure = () => {
console.debug("onGeolocationFailure")
startButton.removeEventListener("click", onStartButtonClick)
} | /** On geolocation failure, remove event listener */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/_welcome.ts#L55-L58 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | getFixTheMapLink | const getFixTheMapLink = ({ lon, lat, zoom }: LonLatZoom): string => {
const zoomRounded = beautifyZoom(zoom)
const precision = zoomPrecision(zoom)
const lonFixed = lon.toFixed(precision)
const latFixed = lat.toFixed(precision)
// TODO: test from within iframe
return `${window.location.origin}/fixthemap?lat=${latFixed}&lon=${lonFixed}&zoom=${zoomRounded}`
} | /**
* Get the fix the map link
* @example
* getFixTheMapLink(5.123456, 6.123456, 17)
* // => "https://www.openstreetmap.org/fixthemap?lat=6.123456&lon=5.123456&zoom=17"
*/ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/embed.ts#L65-L72 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onMoveEnd | const onMoveEnd = () => {
const center = map.getCenter()
const zoom = map.getZoom()
reportProblemLink.href = getFixTheMapLink({ lon: center.lng, lat: center.lat, zoom })
attributionControl.options.customAttribution = reportProblemLink.outerHTML
attributionControl._updateAttributions()
} | /** On move end, update the link with the current coordinates */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/embed.ts#L79-L85 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onMapClick | const onMapClick = ({ lngLat }: { lngLat: LngLat }) => {
console.debug("onMapClick", lngLat)
setMarker(lngLat)
setInput(lngLat)
} | /** On map click, update the coordinates and move the marker */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/diaries/_compose.ts#L60-L64 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onCoordinatesInputChange | const onCoordinatesInputChange = () => {
if (mapDiv.classList.contains("d-none")) return
if (lonInput.value && latInput.value) {
console.debug("onCoordinatesInputChange", lonInput.value, latInput.value)
const lon = Number.parseFloat(lonInput.value)
const lat = Number.parseFloat(latInput.value)
if (isLongitude(lon) && isLatitude(lat)) {
const lngLat: LngLatLike = [lon, lat]
setMarker(lngLat)
// Focus on the makers if it's offscreen
if (!map.getBounds().contains(lngLat)) {
map.panTo(lngLat)
}
}
}
} | /** On coordinates input change, update the marker position */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/diaries/_compose.ts#L67-L82 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onCloseButtonClick | const onCloseButtonClick = () => {
console.debug("configureActionSidebar", "onCloseButtonClick")
routerNavigateStrict("/")
} | /** On sidebar close button click, navigate to index */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_action-sidebar.ts#L31-L34 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | renderElements | const renderElements = (
elementsSection: HTMLElement,
elements: { [key: string]: PartialChangesetParams_Element[] },
): void => {
console.debug("renderElements")
const groupTemplate = elementsSection.querySelector("template.group")
const entryTemplate = elementsSection.querySelector("template.entry")
const fragment = document.createDocumentFragment()
for (const [type, elementsType] of Object.entries(elements)) {
if (!elementsType.length) continue
fragment.appendChild(renderElementType(groupTemplate, entryTemplate, type, elementsType))
}
if (fragment.children.length) {
elementsSection.innerHTML = ""
elementsSection.appendChild(fragment)
} else {
elementsSection.remove()
}
} | /** Render elements component */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_changeset.ts#L108-L129 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | renderElementType | const renderElementType = (
groupTemplate: HTMLTemplateElement,
entryTemplate: HTMLTemplateElement,
type: string,
elements: PartialChangesetParams_Element[],
): DocumentFragment => {
console.debug("renderElementType", type, elements)
const groupFragment = groupTemplate.content.cloneNode(true) as DocumentFragment
const titleElement = groupFragment.querySelector(".title")
const tbody = groupFragment.querySelector("tbody")
// Calculate pagination
const elementsLength = elements.length
const totalPages = Math.ceil(elementsLength / elementsPerPage)
let currentPage = 1
const updateTitle = (): void => {
let count: string
if (totalPages > 1) {
const from = (currentPage - 1) * elementsPerPage + 1
const to = Math.min(currentPage * elementsPerPage, elementsLength)
count = i18next.t("pagination.range", { x: `${from}-${to}`, y: elementsLength })
} else {
count = elementsLength.toString()
}
// Prefer static translation strings to ease automation
let newTitle: string
if (type === "node") {
// @ts-ignore
newTitle = i18next.t("browse.changeset.node", { count })
} else if (type === "way") {
// @ts-ignore
newTitle = i18next.t("browse.changeset.way", { count })
} else if (type === "relation") {
// @ts-ignore
newTitle = i18next.t("browse.changeset.relation", { count })
}
titleElement.textContent = newTitle
}
const updateTable = (): void => {
const tbodyFragment = document.createDocumentFragment()
const iStart = (currentPage - 1) * elementsPerPage
const iEnd = Math.min(currentPage * elementsPerPage, elementsLength)
for (let i = iStart; i < iEnd; i++) {
const element = elements[i]
const entryFragment = entryTemplate.content.cloneNode(true) as DocumentFragment
const iconImg = entryFragment.querySelector("img")
const linkLatest = entryFragment.querySelector("a.link-latest")
const linkVersion = entryFragment.querySelector("a.link-version")
if (element.icon) {
iconImg.src = `/static/img/element/${element.icon.icon}`
iconImg.title = element.icon.title
} else {
iconImg.remove()
}
if (!element.visible) {
linkLatest.parentElement.parentElement.classList.add("deleted")
}
if (element.name) {
const bdi = document.createElement("bdi")
bdi.textContent = element.name
linkLatest.appendChild(bdi)
const span = document.createElement("span")
span.textContent = ` (${element.id})`
linkLatest.appendChild(span)
} else {
linkLatest.textContent = element.id.toString()
}
linkLatest.href = `/${type}/${element.id}`
linkVersion.textContent = `v${element.version}`
linkVersion.href = `/${type}/${element.id}/history/${element.version}`
tbodyFragment.appendChild(entryFragment)
}
tbody.innerHTML = ""
tbody.appendChild(tbodyFragment)
}
// Optionally configure pagination controls
if (totalPages > 1) {
const paginationContainer = groupFragment.querySelector(".pagination")
const updatePagination = (): void => {
console.debug("updatePagination", currentPage)
const paginationFragment = document.createDocumentFragment()
for (let i = 1; i <= totalPages; i++) {
const distance = Math.abs(i - currentPage)
if (distance > paginationDistance && i !== 1 && i !== totalPages) {
if (i === 2 || i === totalPages - 1) {
const li = document.createElement("li")
li.classList.add("page-item", "disabled")
li.ariaDisabled = "true"
li.innerHTML = `<span class="page-link">...</span>`
paginationFragment.appendChild(li)
}
continue
}
const li = document.createElement("li")
li.classList.add("page-item")
const button = document.createElement("button")
button.type = "button"
button.classList.add("page-link")
button.textContent = i.toString()
li.appendChild(button)
if (i === currentPage) {
li.classList.add("active")
li.ariaCurrent = "page"
} else {
button.addEventListener("click", () => {
currentPage = i
updateTitle()
updateTable()
updatePagination()
})
}
paginationFragment.appendChild(li)
}
paginationContainer.innerHTML = ""
paginationContainer.appendChild(paginationFragment)
}
updatePagination()
} else {
groupFragment.querySelector("nav").remove()
}
// Initial update
updateTitle()
updateTable()
return groupFragment
} | /** Render elements of a specific type */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_changeset.ts#L132-L277 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | setHover | const setHover = ({ id, firstFeatureId, numBounds }: GeoJsonProperties, hover: boolean): void => {
const result = idSidebarMap.get(id)
result.classList.toggle("hover", hover)
if (hover) {
// Scroll result into view
const sidebarRect = parentSidebar.getBoundingClientRect()
const resultRect = result.getBoundingClientRect()
const isVisible = resultRect.top >= sidebarRect.top && resultRect.bottom <= sidebarRect.bottom
if (!isVisible) result.scrollIntoView({ behavior: "smooth", block: "center" })
}
for (let i = firstFeatureId; i < firstFeatureId + numBounds * 2; i++) {
map.setFeatureState({ source: layerId, id: i }, { hover })
}
} | /** Set the hover state of the changeset features */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_changesets-history.ts#L169-L182 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onSidebarScroll | const onSidebarScroll = (): void => {
if (parentSidebar.offsetHeight + parentSidebar.scrollTop < parentSidebar.scrollHeight) return
console.debug("Sidebar scrolled to the bottom")
updateState()
} | /** On sidebar scroll bottom, load more changesets */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_changesets-history.ts#L213-L217 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | updateState | const updateState = (): void => {
// Request full world when initial loading for scope/user
const fetchBounds = fetchedBounds || (!loadScope && !loadDisplayName) ? map.getBounds() : null
const params: { [key: string]: string | undefined } = { scope: loadScope, display_name: loadDisplayName }
if (fetchedBounds === fetchBounds) {
// Load more changesets
if (noMoreChangesets) return
params.before = changesets[changesets.length - 1].id.toString()
} else {
// Ignore small bounds changes
if (fetchedBounds && fetchBounds) {
const visibleBounds = getLngLatBoundsIntersection(fetchedBounds, fetchBounds)
const visibleArea = getLngLatBoundsSize(visibleBounds)
const fetchArea = getLngLatBoundsSize(fetchBounds)
const proportion = visibleArea / Math.max(getLngLatBoundsSize(fetchedBounds), fetchArea)
if (proportion > reloadProportionThreshold) return
}
// Clear the changesets if the bbox changed
changesets.length = 0
noMoreChangesets = false
entryContainer.innerHTML = ""
}
if (fetchBounds) {
const [[minLon, minLat], [maxLon, maxLat]] = fetchBounds.adjustAntiMeridian().toArray()
params.bbox = `${minLon},${minLat},${maxLon},${maxLat}`
}
loadingContainer.classList.remove("d-none")
parentSidebar.removeEventListener("scroll", onSidebarScroll)
// Abort any pending request
abortController?.abort()
abortController = new AbortController()
const signal = abortController.signal
fetch(`/api/web/changeset/map?${qsEncode(params)}`, {
method: "GET",
mode: "same-origin",
cache: "no-store", // request params are too volatile to cache
signal: signal,
priority: "high",
})
.then(async (resp) => {
if (!resp.ok) throw new Error(`${resp.status} ${resp.statusText}`)
const buffer = await resp.arrayBuffer()
const newChangesets = fromBinary(RenderChangesetsDataSchema, new Uint8Array(buffer)).changesets
if (newChangesets.length) {
changesets.push(...newChangesets)
console.debug(
"Changesets layer showing",
changesets.length,
"changesets, including",
newChangesets.length,
"new",
)
} else {
console.debug("No more changesets")
noMoreChangesets = true
}
updateLayers()
updateSidebar()
fetchedBounds = fetchBounds
})
.catch((error) => {
if (error.name === "AbortError") return
console.error("Failed to fetch map data", error)
source.setData(emptyFeatureCollection)
changesets.length = 0
noMoreChangesets = false
})
.finally(() => {
if (signal.aborted) return
loadingContainer.classList.add("d-none")
parentSidebar.addEventListener("scroll", onSidebarScroll)
})
} | /** On map update, fetch the changesets in view and update the changesets layer */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_changesets-history.ts#L220-L298 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | updateUrl | const updateUrl = (dirtyIndices: number[]): void => {
const newLength = markers.length
if (newLength < positionsUrl.length) {
// Truncate positions
positionsUrl.length = newLength
}
for (const markerIndex of dirtyIndices) {
const lngLat = markers[markerIndex].getLngLat()
positionsUrl[markerIndex] = [lngLat.lng, lngLat.lat]
}
throttledUpdateHistory()
} | // Encodes current marker positions into URL polyline parameter | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_distance.ts#L108-L120 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | updateLines | const updateLines = (dirtyIndices: number[]): void => {
const newLength = Math.max(markers.length - 1, 0)
if (newLength < lines.length) {
// Truncate lines
lines.length = newLength
}
for (const markerIndex of dirtyIndices) {
const lineIndex = markerIndex - 1
if (lineIndex >= lines.length) {
// Create new line
lines[lineIndex] = {
type: "Feature",
id: lineIndex,
properties: {},
geometry: {
type: "LineString",
coordinates: [
markers[markerIndex - 1].getLngLat().toArray(),
markers[markerIndex].getLngLat().toArray(),
],
},
}
}
for (const lineIndexOffset of [lineIndex, lineIndex + 1]) {
// Update existing line (before and after)
if (lineIndexOffset < 0 || lineIndexOffset >= lines.length) continue
lines[lineIndexOffset].geometry.coordinates = [
markers[lineIndexOffset].getLngLat().toArray(),
markers[lineIndexOffset + 1].getLngLat().toArray(),
]
}
}
source.setData({
type: "FeatureCollection",
features: lines,
})
} | // Updates GeoJSON line features between consecutive markers | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_distance.ts#L129-L165 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | updateLabels | const updateLabels = (dirtyIndices: number[]): void => {
const newLength = Math.max(markers.length - 1, 0)
if (newLength < labels.length) {
// Truncate labels
for (let i = newLength; i < labels.length; i++) labels[i].remove()
labels.length = newLength
}
for (const markerIndex of dirtyIndices) {
const labelIndex = markerIndex - 1
if (labelIndex >= labels.length) {
// Create new label
labels[labelIndex] = new Marker({
anchor: "center",
element: document.createElement("div"),
className: "distance-label",
})
.setLngLat([0, 0])
.addTo(map)
}
for (const labelIndexOffset of [labelIndex, labelIndex + 1]) {
// Update existing label (before and after)
if (labelIndexOffset < 0 || labelIndexOffset >= labels.length) continue
const startPoint = markers[labelIndexOffset].getLngLat()
const startScreenPoint = map.project(startPoint)
const endPoint = markers[labelIndexOffset + 1].getLngLat()
const endScreenPoint = map.project(endPoint)
// Calculate middle point
// TODO: make sure this works correctly with 3d globe (#155)
const middlePoint = map.unproject(
new Point(
(startScreenPoint.x + endScreenPoint.x) / 2, //
(startScreenPoint.y + endScreenPoint.y) / 2,
),
)
let angle = Math.atan2(endScreenPoint.y - startScreenPoint.y, endScreenPoint.x - startScreenPoint.x)
if (angle > Math.PI / 2) angle -= Math.PI
if (angle < -Math.PI / 2) angle += Math.PI
const label = labels[labelIndexOffset]
label.setLngLat(middlePoint)
const distance = startPoint.distanceTo(endPoint)
;(label as any).distance = distance
label.setRotation((angle * 180) / Math.PI)
label.getElement().textContent = formatDistance(distance)
}
}
let totalDistance = 0
for (const label of labels) totalDistance += (label as any).distance
totalDistanceLabel.textContent = formatDistance(totalDistance)
} | // Updates distance labels and calculates total measurement | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_distance.ts#L168-L220 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | update | const update = (dirtyIndices: number[]): void => {
updateUrl(dirtyIndices)
updateLines(dirtyIndices)
updateLabels(dirtyIndices)
clearBtn.classList.toggle("d-none", !markers.length)
} | // Schedule updates to all components after marker changes, dirtyIndices must be sorted | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_distance.ts#L223-L229 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | removeMarker | const removeMarker = (index: number): void => {
console.debug("Remove distance marker", index)
// Pop tailing markers
const tail = markers.splice(index + 1)
{
// Remove indexed marker
const marker = markers[index]
marker.remove()
markers.length = index
}
update([])
if (tail.length) {
// Add markers back
for (const marker of tail) {
const lngLat = marker.getLngLat()
marker.remove()
createNewMarker({ lngLat, skipUpdates: true })
}
update(range(index, markers.length))
} else if (index >= 2) {
// If no tail, turn previous marker into red
markers[index - 1].getElement().replaceChildren(...getMarkerIconElement("red", true).children)
}
} | // Removes a marker and updates subsequent geometry | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_distance.ts#L239-L263 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | insertMarker | const insertMarker = (index: number, lngLat: LngLatLike) => {
console.debug("Insert distance marker", index, lngLat)
// Pop tailing markers
const tail = markers.splice(index)
update([])
// Add new marker
createNewMarker({ lngLat, skipUpdates: true })
// Add markers back
for (const marker of tail) {
const markerLngLat = marker.getLngLat()
marker.remove()
createNewMarker({ lngLat: markerLngLat, skipUpdates: true })
}
update(range(index, markers.length))
} | // Inserts new marker at specified position and updates connections | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_distance.ts#L266-L282 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | createNewMarker | const createNewMarker = ({ lngLat, skipUpdates }: { lngLat: LngLatLike; skipUpdates?: boolean }): void => {
// Avoid event handlers after the controller is unloaded
if (!hasMapLayer(map, layerId)) return
console.debug("Create distance marker", lngLat, skipUpdates)
const markerIndex = markers.length
// Turn previous marker into blue
if (markerIndex >= 2) {
markers[markerIndex - 1].getElement().replaceChildren(...getMarkerIconElement("blue", true).children)
}
// Create new marker
const marker = markerFactory(markerIndex, markerIndex === 0 ? "green" : "red")
.setLngLat(lngLat)
.addTo(map)
markers.push(marker)
if (!skipUpdates) update([markerIndex])
} | // Adds new endpoint marker and updates visualization | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_distance.ts#L285-L300 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | startGhostMarkerDrag | const startGhostMarkerDrag = () => {
console.debug("materializeGhostMarker")
ghostMarker.removeClassName("d-none")
ghostMarker.addClassName("dragging")
// Add a real marker
insertMarker(ghostMarkerIndex, ghostMarker.getLngLat())
} | /** On ghost marker drag start, replace it with a real marker */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_distance.ts#L362-L368 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onGhostMarkerClick | const onGhostMarkerClick = (e: MouseEvent) => {
e.stopPropagation()
console.debug("onGhostMarkerClick")
startGhostMarkerDrag()
ghostMarker.removeClassName("dragging")
ghostMarker.addClassName("d-none")
} | /** On ghost marker click, convert it into a real marker */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_distance.ts#L379-L385 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | renderElementsComponent | const renderElementsComponent = (
elementsSection: HTMLElement,
elements: PartialElementParams_Entry[],
isWay: boolean,
): void => {
console.debug("renderElementsComponent", elements.length)
const entryTemplate = elementsSection.querySelector("template.entry")
const titleElement = elementsSection.querySelector(".title")
const tbody = elementsSection.querySelector("tbody")
// Calculate pagination
const elementsLength = elements.length
const totalPages = Math.ceil(elementsLength / elementsPerPage)
let currentPage = 1
const updateTitle = (): void => {
let count: string
if (totalPages > 1) {
const from = (currentPage - 1) * elementsPerPage + 1
const to = Math.min(currentPage * elementsPerPage, elementsLength)
count = i18next.t("pagination.range", { x: `${from}-${to}`, y: elementsLength })
} else {
count = elementsLength.toString()
}
// Prefer static translation strings to ease automation
let newTitle: string
if (isWay) {
// @ts-ignore
newTitle = i18next.t("browse.changeset.node", { count })
} else if (elementsSection.classList.contains("parents")) {
newTitle = `${i18next.t("browse.part_of")} (${count})`
} else {
newTitle = `${i18next.t("browse.relation.members")} (${count})`
}
titleElement.textContent = newTitle
}
const updateTable = (): void => {
const tbodyFragment = document.createDocumentFragment()
const iStart = (currentPage - 1) * elementsPerPage
const iEnd = Math.min(currentPage * elementsPerPage, elementsLength)
for (let i = iStart; i < iEnd; i++) {
const element = elements[i]
const type = element.type
const entryFragment = entryTemplate.content.cloneNode(true) as DocumentFragment
const iconImg = entryFragment.querySelector("img")
const content = entryFragment.querySelector("td:last-child")
if (element.icon) {
iconImg.src = `/static/img/element/${element.icon.icon}`
iconImg.title = element.icon.title
} else {
iconImg.remove()
}
// Prefer static translation strings to ease automation
let typeStr: string
if (type === "node") {
typeStr = i18next.t("javascripts.query.node")
} else if (type === "way") {
typeStr = i18next.t("javascripts.query.way")
} else if (type === "relation") {
typeStr = i18next.t("javascripts.query.relation")
}
const linkLatest = document.createElement("a")
if (element.name) {
const bdi = document.createElement("bdi")
bdi.textContent = element.name
linkLatest.appendChild(bdi)
const span = document.createElement("span")
span.textContent = ` (${element.id})`
linkLatest.appendChild(span)
} else {
linkLatest.textContent = element.id.toString()
}
linkLatest.href = `/${type}/${element.id}`
if (isWay) {
content.appendChild(linkLatest)
} else if (element.role) {
content.innerHTML = i18next.t("browse.relation_member.entry_role_html", {
type: typeStr,
name: linkLatest.outerHTML,
role: element.role,
interpolation: { escapeValue: false },
})
} else {
content.innerHTML = i18next.t("browse.relation_member.entry_html", {
type: typeStr,
name: linkLatest.outerHTML,
interpolation: { escapeValue: false },
})
}
tbodyFragment.appendChild(entryFragment)
}
tbody.innerHTML = ""
tbody.appendChild(tbodyFragment)
}
if (totalPages > 1) {
const paginationContainer = elementsSection.querySelector(".pagination")
const updatePagination = (): void => {
console.debug("updatePagination", currentPage)
const paginationFragment = document.createDocumentFragment()
for (let i = 1; i <= totalPages; i++) {
const distance = Math.abs(i - currentPage)
if (distance > paginationDistance && i !== 1 && i !== totalPages) {
if (i === 2 || i === totalPages - 1) {
const li = document.createElement("li")
li.classList.add("page-item", "disabled")
li.ariaDisabled = "true"
li.innerHTML = `<span class="page-link">...</span>`
paginationFragment.appendChild(li)
}
continue
}
const li = document.createElement("li")
li.classList.add("page-item")
const button = document.createElement("button")
button.type = "button"
button.classList.add("page-link")
button.textContent = i.toString()
li.appendChild(button)
if (i === currentPage) {
li.classList.add("active")
li.ariaCurrent = "page"
} else {
button.addEventListener("click", () => {
currentPage = i
updateTitle()
updateTable()
updatePagination()
})
}
paginationFragment.appendChild(li)
}
paginationContainer.innerHTML = ""
paginationContainer.appendChild(paginationFragment)
}
updatePagination()
} else {
elementsSection.querySelector("nav").remove()
}
// Initial update
updateTitle()
updateTable()
} | /** Render elements component */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_element.ts#L90-L253 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | updateState | const updateState = () => {
const precision = zoomPrecision(map.getZoom())
const bounds = customRegionCheckbox.checked ? locationFilter.getBounds() : map.getBounds()
const [[minLon, minLat], [maxLon, maxLat]] = bounds.adjustAntiMeridian().toArray()
minLonInput.value = minLon.toFixed(precision)
minLatInput.value = minLat.toFixed(precision)
maxLonInput.value = maxLon.toFixed(precision)
maxLatInput.value = maxLat.toFixed(precision)
updateElements(minLon, minLat, maxLon, maxLat)
} | /** On map move end, update the inputs */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_export.ts#L46-L55 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | updateButtonState | const updateButtonState = () => {
const hasValue = commentInput.value.trim().length > 0
submitButton.disabled = !hasValue
} | /** On comment input, update the button state */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_new-note.ts#L38-L41 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onFormSuccess | const onFormSuccess = () => {
map.panBy([0, 0], { animate: false })
controller.unload()
controller.load({ id: params.id.toString() })
} | /** On success callback, reload the note and simulate map move (reload notes layer) */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_note.ts#L89-L93 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onSubmitClick | const onSubmitClick = ({ target }: MouseEvent) => {
eventInput.value = (target as HTMLButtonElement).dataset.event
} | /** On submit click, set event type */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_note.ts#L99-L101 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onCommentInput | const onCommentInput = () => {
const hasValue = commentInput.value.trim().length > 0
if (hasValue) {
closeButton.classList.add("d-none")
commentCloseButton.classList.remove("d-none")
commentButton.disabled = false
} else {
closeButton.classList.remove("d-none")
commentCloseButton.classList.add("d-none")
commentButton.disabled = true
}
} | /** On comment input, update the button state */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_note.ts#L106-L117 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | getURLQueryPosition | const getURLQueryPosition = (): LonLatZoom | null => {
const searchParams = qsParse(location.search.substring(1))
if (searchParams.lon && searchParams.lat) {
const lon = Number.parseFloat(searchParams.lon)
const lat = Number.parseFloat(searchParams.lat)
const zoom = Math.max(
searchParams.zoom ? Number.parseFloat(searchParams.zoom) : map.getZoom(),
queryFeaturesMinZoom,
)
if (isLongitude(lon) && isLatitude(lat) && isZoom(zoom)) {
return { lon, lat, zoom }
}
}
return null
} | /** Get query position from URL */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_query-features.ts#L74-L88 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | configureResultActions | const configureResultActions = (container: HTMLElement): void => {
const queryList = container.querySelector("ul.search-list")
const resultActions = queryList.querySelectorAll("li.social-action")
const params = fromBinary(PartialQueryFeaturesParamsSchema, base64Decode(queryList.dataset.params))
for (let i = 0; i < resultActions.length; i++) {
const resultAction = resultActions[i]
const render = params.renders[i]
const elements = staticCache(() => convertRenderElementsData(render))
resultAction.addEventListener("mouseenter", () => focusObjects(map, elements(), focusPaint))
resultAction.addEventListener("mouseleave", () => focusObjects(map)) // remove focus
}
} | /** Configure result actions to handle focus and clicks */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_query-features.ts#L91-L102 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onSidebarLoading | const onSidebarLoading = (center: LngLat, zoom: number, abortSignal: AbortSignal): void => {
nearbyContainer.innerHTML = nearbyLoadingHtml
enclosingContainer.innerHTML = enclosingLoadingHtml
const radiusMeters = 10 * 1.5 ** (19 - zoom)
console.debug("Query features radius", radiusMeters, "meters")
source.setData(getCircleFeature(center, radiusMeters))
// Fade out circle smoothly
const animationDuration = 750
const fillLayerId = getExtendedLayerId(layerId, "fill")
const lineLayerId = getExtendedLayerId(layerId, "line")
const fadeOut = (timestamp?: DOMHighResTimeStamp) => {
const currentTime = timestamp ?? performance.now()
if (currentTime < animationStart) animationStart = currentTime
const elapsedTime = currentTime - animationStart
let opacity = 1 - Math.min(elapsedTime / animationDuration, 1)
if (prefersReducedMotion) opacity = opacity > 0 ? 1 : 0
map.setPaintProperty(fillLayerId, "fill-opacity", opacity * 0.4)
map.setPaintProperty(lineLayerId, "line-opacity", opacity)
if (opacity > 0 && !abortSignal.aborted) requestAnimationFramePolyfill(fadeOut)
else {
removeMapLayer(map, layerId, false)
source.setData(emptyFeatureCollection)
}
}
addMapLayer(map, layerId, false)
let animationStart = performance.now()
requestAnimationFramePolyfill(fadeOut)
} | /** On sidebar loading, display loading content and show map animation */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_query-features.ts#L105-L134 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onSidebarNearbyLoaded | const onSidebarNearbyLoaded = (html: string): void => {
nearbyContainer.innerHTML = html
configureResultActions(nearbyContainer)
} | /** On sidebar loaded, display content */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_query-features.ts#L137-L140 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onSidebarEnclosingLoaded | const onSidebarEnclosingLoaded = (html: string): void => {
enclosingContainer.innerHTML = html
configureResultActions(enclosingContainer)
} | /** On sidebar loaded, display content */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_query-features.ts#L143-L146 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | findRoute | const findRoute = (path: string): Route | undefined => routes.find((route) => route.match(path)) | /** Find the first route that matches a path */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_router.ts#L13-L13 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | removeTrailingSlash | const removeTrailingSlash = (str: string): string =>
str.endsWith("/") && str.length > 1 ? removeTrailingSlash(str.slice(0, -1)) : str | /**
* Remove trailing slash from a string
* @example
* removeTrailingSlash("/way/1234/")
* // => "/way/1234"
*/ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_router.ts#L21-L22 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onInterfaceMarkerDragStart | const onInterfaceMarkerDragStart = (event: DragEvent) => {
const target = event.target as HTMLImageElement
const direction = target.dataset.direction
console.debug("onInterfaceMarkerDragStart", direction)
const dt = event.dataTransfer
dt.effectAllowed = "move"
dt.setData("text/plain", "")
dt.setData(dragDataType, direction)
const canvas = document.createElement("canvas")
canvas.width = 25
canvas.height = 41
const ctx = canvas.getContext("2d")
ctx.drawImage(target, 0, 0, 25, 41)
dt.setDragImage(canvas, 12, 21)
} | /** On draggable marker drag start, set data and drag image */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_routing.ts#L110-L125 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | setHover | const setHover = (id: number, hover: boolean): void => {
const result = stepsTableBody.children[id]
result.classList.toggle("hover", hover)
if (hover) {
// Scroll result into view
const sidebarRect = sidebar.getBoundingClientRect()
const resultRect = result.getBoundingClientRect()
const isVisible = resultRect.top >= sidebarRect.top && resultRect.bottom <= sidebarRect.bottom
if (!isVisible) result.scrollIntoView({ behavior: "smooth", block: "center" })
}
map.setFeatureState({ source: layerId, id: id }, { hover })
} | /** Set the hover state of the step features */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_routing.ts#L163-L174 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onMapMarkerDragEnd | const onMapMarkerDragEnd = (lngLat: LngLat, isStart: boolean): void => {
console.debug("onMapMarkerDragEnd", lngLat, isStart)
const precision = zoomPrecision(map.getZoom())
const lon = lngLat.lng.toFixed(precision)
const lat = lngLat.lat.toFixed(precision)
const value = `${lat}, ${lon}`
if (isStart) {
startInput.value = value
startInput.dispatchEvent(new Event("input"))
} else {
endInput.value = value
endInput.dispatchEvent(new Event("input"))
}
submitFormIfFilled()
} | /** On marker drag end, update the form's coordinates */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_routing.ts#L177-L194 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onMapDragOver | const onMapDragOver = (event: DragEvent) => event.preventDefault() | /** On map drag over, prevent default behavior */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_routing.ts#L197-L197 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onMapDrop | const onMapDrop = (event: DragEvent) => {
const dragData = event.dataTransfer.getData(dragDataType)
console.debug("onMapDrop", dragData)
let marker: Marker
if (dragData === "start") {
if (!startMarker) {
startMarker = markerFactory("green")
startMarker.on("dragend", () => onMapMarkerDragEnd(startMarker.getLngLat(), true))
}
marker = startMarker
} else if (dragData === "end") {
if (!endMarker) {
endMarker = markerFactory("red")
endMarker.on("dragend", () => onMapMarkerDragEnd(endMarker.getLngLat(), false))
}
marker = endMarker
} else {
return
}
const mapRect = mapContainer.getBoundingClientRect()
const mousePoint = new Point(event.clientX - mapRect.left, event.clientY - mapRect.top)
marker.setLngLat(map.unproject(mousePoint)).addTo(map).fire("dragend")
} | /** On map marker drop, update the marker's coordinates */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_routing.ts#L200-L224 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onMapZoomOrMoveEnd | const onMapZoomOrMoveEnd = () => {
const [[minLon, minLat], [maxLon, maxLat]] = map.getBounds().adjustAntiMeridian().toArray()
bboxInput.value = `${minLon},${minLat},${maxLon},${maxLat}`
} | /** On map update, update the form's bounding box */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_routing.ts#L227-L230 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | submitFormIfFilled | const submitFormIfFilled = () => {
popup.remove()
if (startInput.value && endInput.value) form.requestSubmit()
} | /** Utility method to submit the form if filled with data */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_routing.ts#L265-L268 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | getInitialRoutingEngine | const getInitialRoutingEngine = (engine?: string): string | null => {
return engine ?? getLastRoutingEngine()
} | /** Get initial routing engine identifier */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_routing.ts#L509-L511 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onSearchAlertClick | const onSearchAlertClick = () => {
console.debug("Searching within new area")
controller.unload()
if (whereIsThisMode) {
const center = map.getCenter()
const zoom = map.getZoom()
const precision = zoomPrecision(zoom)
controller.load({
lon: center.lng.toFixed(precision),
lat: center.lat.toFixed(precision),
zoom: beautifyZoom(zoom),
})
} else {
controller.load({ localOnly: "1" })
}
} | /** On search alert click, reload the search with the new area */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_search.ts#L106-L121 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onMapZoomOrMoveEnd | const onMapZoomOrMoveEnd = () => {
if (!initialBounds) {
initialBounds = map.getBounds()
console.debug("Search initial bounds set to", initialBounds)
return
}
if (!searchAlert.classList.contains("d-none")) return
const initialBoundsSize = getLngLatBoundsSize(initialBounds)
const mapBounds = map.getBounds()
const mapBoundsSize = getLngLatBoundsSize(mapBounds)
const intersectionBounds = getLngLatBoundsIntersection(initialBounds, mapBounds)
const intersectionBoundsSize = getLngLatBoundsSize(intersectionBounds)
const proportion = Math.min(intersectionBoundsSize / mapBoundsSize, intersectionBoundsSize / initialBoundsSize)
if (proportion > searchAlertChangeThreshold) return
searchAlert.classList.remove("d-none")
map.off("moveend", onMapZoomOrMoveEnd)
} | /** On map update, check if view was changed and show alert if so */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/index/_search.ts#L124-L143 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | getPopupPosition | const getPopupPosition = (): { lon: string; lat: string; zoom: number } => {
const zoom = map.getZoom()
const precision = zoomPrecision(zoom)
const lngLat = popup.getLngLat()
return {
lon: lngLat.lng.toFixed(precision),
lat: lngLat.lat.toFixed(precision),
zoom,
}
} | /**
* Get the simplified position of the popup
* @example
* getPopupPosition()
* // => { lon: "12.345678", lat: "23.456789", zoom: 17 }
*/ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_context-menu.ts#L44-L53 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | closePopup | const closePopup = () => {
dropdown.hide()
popup.remove()
} | /** On map interactions, close the popup */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_context-menu.ts#L56-L59 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onGeolocationFieldClick | const onGeolocationFieldClick = async ({ target }: Event) => {
closePopup()
try {
const value = (target as Element).textContent
await navigator.clipboard.writeText(value)
console.debug("Copied geolocation to clipboard", value)
} catch (err) {
console.warn("Failed to copy geolocation", err)
}
} | /** On geolocation field click, copy the text content */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_context-menu.ts#L94-L103 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onFeatureClick | const onFeatureClick = (e: MapLayerMouseEvent): void => {
const props = e.features[0].properties
routerNavigateStrict(`/${props.type}/${props.id}`)
} | /** On feature click, navigate to the object page */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_data-layer.ts#L79-L82 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | loadData | const loadData = (): void => {
console.debug("Loading", fetchedElements.length, "elements")
loadDataAlert.classList.add("d-none")
source.setData(renderObjects(fetchedElements, { renderAreas: false }))
} | /** Load map data into the data layer */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_data-layer.ts#L111-L115 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | showDataAlert | const showDataAlert = (): void => {
console.debug("Requested too much data, showing alert")
if (!loadDataAlert.classList.contains("d-none")) return
showDataButton.addEventListener("click", onShowDataButtonClick, { once: true })
hideDataButton.addEventListener("click", onHideDataButtonClick, { once: true })
loadDataAlert.classList.remove("d-none")
} | /** Display data alert if not already shown */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_data-layer.ts#L118-L124 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onShowDataButtonClick | const onShowDataButtonClick = () => {
if (loadDataOverride) return
console.debug("onShowDataButtonClick")
loadDataOverride = true
loadDataAlert.classList.add("d-none")
fetchedElements = []
fetchedBounds = null
updateLayer()
} | /** On show data click, mark override and load data */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_data-layer.ts#L127-L135 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | onHideDataButtonClick | const onHideDataButtonClick = () => {
if (dataOverlayCheckbox.checked === false) return
console.debug("onHideDataButtonClick")
dataOverlayCheckbox.checked = false
dataOverlayCheckbox.dispatchEvent(new Event("change"))
loadDataAlert.classList.add("d-none")
} | /** On hide data click, uncheck the data layer checkbox */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_data-layer.ts#L138-L144 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | updateLayer | const updateLayer = (): void => {
// Skip if the notes layer is not visible
if (!enabled) return
// Abort any pending request
abortController?.abort()
abortController = new AbortController()
const viewBounds = map.getBounds()
// Skip updates if the view is satisfied
if (
fetchedBounds?.contains(viewBounds.getSouthWest()) &&
fetchedBounds.contains(viewBounds.getNorthEast()) &&
loadDataAlert.classList.contains("d-none")
)
return
// Pad the bounds to reduce refreshes
const fetchBounds = padLngLatBounds(viewBounds, 0.3)
// Skip updates if the area is too big
const area = getLngLatBoundsSize(fetchBounds)
if (area > config.mapQueryAreaMaxSize) {
errorDataAlert.classList.remove("d-none")
loadDataAlert.classList.add("d-none")
clearData()
return
}
errorDataAlert.classList.add("d-none")
const [[minLon, minLat], [maxLon, maxLat]] = fetchBounds.adjustAntiMeridian().toArray()
fetch(
`/api/web/map?${qsEncode({
bbox: `${minLon},${minLat},${maxLon},${maxLat}`,
limit: loadDataOverride ? "" : loadDataAlertThreshold.toString(),
})}`,
{
method: "GET",
mode: "same-origin",
cache: "no-store", // request params are too volatile to cache
signal: abortController.signal,
priority: "high",
},
)
.then(async (resp) => {
if (!resp.ok) {
if (resp.status === 400) {
errorDataAlert.classList.remove("d-none")
loadDataAlert.classList.add("d-none")
clearData()
return
}
throw new Error(`${resp.status} ${resp.statusText}`)
}
const buffer = await resp.arrayBuffer()
const render = fromBinary(RenderElementsDataSchema, new Uint8Array(buffer))
fetchedElements = convertRenderElementsData(render)
fetchedBounds = fetchBounds
if (render.tooMuchData) {
showDataAlert()
} else {
loadData()
}
})
.catch((error) => {
if (error.name === "AbortError") return
console.error("Failed to fetch map data", error)
clearData()
})
} | /** On map update, fetch the elements in view and update the data layer */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_data-layer.ts#L147-L218 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | getImageTrim | const getImageTrim = (
map: MaplibreMap,
width: number,
height: number,
mapBounds: LngLatBounds,
filterBounds: LngLatBounds,
): { top: number; left: number; bottom: number; right: number } => {
filterBounds = getLngLatBoundsIntersection(mapBounds, filterBounds)
if (filterBounds.isEmpty()) {
return { top: 0, left: 0, bottom: 0, right: 0 }
}
const bottomLeft = map.project(filterBounds.getSouthWest())
const topRight = map.project(filterBounds.getNorthEast())
const ratio = window.devicePixelRatio
return {
top: Math.ceil(topRight.y * ratio),
left: Math.ceil(bottomLeft.x * ratio),
bottom: Math.ceil(height - bottomLeft.y * ratio),
right: Math.ceil(width - topRight.x * ratio),
}
} | /** Calculate the offsets for trimming the exported image */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_export-image.ts#L145-L165 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | createMainMap | const createMainMap = (container: HTMLElement): MaplibreMap => {
console.debug("Initializing main map")
const map = new MaplibreMap({
container,
maxZoom: 19,
attributionControl: { compact: true, customAttribution: "" },
refreshExpiredTiles: false,
canvasContextAttributes: { alpha: false, preserveDrawingBuffer: true },
fadeDuration: 0,
})
map.once("style.load", () => {
// Disable transitions after loading the style
map.style.stylesheet.transition = { duration: 0 }
})
configureDefaultMapBehavior(map)
addMapLayerSources(map, "all")
configureNotesLayer(map)
configureDataLayer(map)
configureContextMenu(map)
const saveMapStateLazy = wrapIdleCallbackStatic(() => {
const state = getMapState(map)
updateNavbarAndHash(state)
setLastMapState(state)
})
map.on("moveend", saveMapStateLazy)
addLayerEventHandler(saveMapStateLazy)
// Add controls to the map
map.addControl(
new ScaleControl({
unit: isMetricUnit() ? "metric" : "imperial",
}),
)
addControlGroup(map, [new CustomZoomControl(), new CustomGeolocateControl()])
addControlGroup(map, [
new LayersSidebarToggleControl(),
new LegendSidebarToggleControl(),
new ShareSidebarToggleControl(),
])
addControlGroup(map, [new NewNoteControl()])
addControlGroup(map, [new QueryFeaturesControl()])
// On hash change, update the map view
window.addEventListener("hashchange", () => {
// TODO: check if no double setMapState triggered
console.debug("onHashChange", location.hash)
let newState = parseMapState(location.hash)
if (!newState) {
// Get the current state if empty/invalid and replace the hash
newState = getMapState(map)
updateNavbarAndHash(newState)
}
setMapState(map, newState)
})
// Finally set the initial state that will trigger map events
setMapState(map, getInitialMapState(map), { animate: false })
return map
} | /** Get the main map instance */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_main-map.ts#L37-L96 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | configureMainMap | const configureMainMap = (container: HTMLElement): void => {
const map = createMainMap(container)
// Configure here instead of navbar to avoid global script dependency (navbar is global)
// Find home button is only available for the users with configured home location
const homePoint = config.userConfig?.homePoint
if (homePoint) {
const findHomeContainer = document.querySelector(".find-home-container")
const findHomeButton = findHomeContainer.querySelector("button")
configureFindHomeButton(map, findHomeButton, homePoint)
findHomeContainer.classList.remove("d-none")
}
configureRouter(
new Map<string, IndexController>([
["/", getIndexController(map)],
["/export", getExportController(map)],
["/directions", getRoutingController(map)],
["/search", getSearchController(map)],
["/query", getQueryFeaturesController(map)],
[
"(?:/history(?:/(?<scope>nearby|friends))?|/user/(?<displayName>[^/]+)/history)",
getChangesetsHistoryController(map),
],
["/note/new", getNewNoteController(map)],
["/note/(?<id>\\d+)", getNoteController(map)],
["/changeset/(?<id>\\d+)", getChangesetController(map)],
["/(?<type>node|way|relation)/(?<id>\\d+)(?:/history/(?<version>\\d+))?", getElementController(map)],
["/(?<type>node|way|relation)/(?<id>\\d+)/history", getElementHistoryController(map)],
["/distance", getDistanceController(map)],
]),
)
configureSearchForm(map)
handleEditRemotePath()
} | /** Configure the main map and all its components */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_main-map.ts#L99-L134 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | setMapLayersCode | const setMapLayersCode = (map: MaplibreMap, layersCode?: string): void => {
console.debug("setMapLayersCode", layersCode)
const addLayerCodes: Set<LayerCode> = new Set()
let hasBaseLayer = false
for (const layerCode of (layersCode || "") as Iterable<LayerCode>) {
const layerId = resolveLayerCodeOrId(layerCode)
if (!layerId) continue
addLayerCodes.add(layerCode)
if (layersConfig.get(layerId).isBaseLayer) {
if (hasBaseLayer) {
console.error("Invalid layers code", layersCode, "(too many base layers)")
return
}
hasBaseLayer = true
}
}
// Add default base layer if no base layer is present
if (!hasBaseLayer) addLayerCodes.add("" as LayerCode)
// Remove layers not found in the code
const missingLayerCodes: Set<LayerCode> = new Set(addLayerCodes)
for (const extendedLayerId of map.getLayersOrder()) {
const layerId = resolveExtendedLayerId(extendedLayerId)
if (!layerId) continue
const layerCode = layersConfig.get(layerId).layerCode
if (layerCode === undefined || addLayerCodes.has(layerCode)) {
console.debug("Keeping layer", layerId)
missingLayerCodes.delete(layerCode)
continue
}
removeMapLayer(map, layerId)
}
// Add missing layers
for (const layerCode of missingLayerCodes) {
addMapLayer(map, resolveLayerCodeOrId(layerCode))
}
} | /**
* Set the map layers from a layers code
* @example
* setMapLayersCode(map, "BT")
*/ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_map-utils.ts#L56-L95 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | convertBoundsToLonLatZoom | const convertBoundsToLonLatZoom = (map: MaplibreMap | null, bounds: Bounds): LonLatZoom => {
const [minLon, minLat, maxLon, maxLat] = bounds
const lon = (minLon + maxLon) / 2
const lat = (minLat + maxLat) / 2
if (map) {
const camera = map.cameraForBounds([minLon, minLat, maxLon, maxLat])
if (camera) return { lon, lat, zoom: camera.zoom }
}
const latRad = (lat: number): number => Math.sin((lat * Math.PI) / 180)
const getZoom = (mapPx: number, worldPx: number, fraction: number): number =>
(Math.log(mapPx / worldPx / fraction) / Math.LN2) | 0
// Calculate the fraction of the world that the longitude and latitude take up
const latFraction = (latRad(maxLat) - latRad(minLat)) / Math.PI
const lonDiff = maxLon - minLon
const lonFraction = (lonDiff < 0 ? lonDiff + 360 : lonDiff) / 360
// Assume the map takes up the entire screen
const mapHeight = window.innerHeight
const mapWidth = window.innerWidth
// Calculate the maximum zoom level at which the entire bounds would fit in the map view
const tileSize = 256
const maxLatZoom = getZoom(mapHeight, tileSize, latFraction)
const maxLonZoom = getZoom(mapWidth, tileSize, lonFraction)
const zoom = Math.min(maxLatZoom, maxLonZoom)
return { lon, lat, zoom }
} | /** Convert bounds to a lon, lat, zoom object */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_map-utils.ts#L188-L217 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | updateState | const updateState = () => {
const zoom = map.getZoom()
if (zoom < newNoteMinZoom) {
if (!button.disabled) {
button.blur()
button.disabled = true
Tooltip.getInstance(button).setContent({
".tooltip-inner": i18next.t("javascripts.site.createnote_disabled_tooltip"),
})
}
} else if (button.disabled) {
button.disabled = false
Tooltip.getInstance(button).setContent({
".tooltip-inner": i18next.t("javascripts.site.createnote_tooltip"),
})
}
} | /** On map zoom, change button availability */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_new-note.ts#L46-L62 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | updateLayer | const updateLayer = (): void => {
// Skip if the notes layer is not visible
if (!enabled) return
// Abort any pending request
abortController?.abort()
abortController = new AbortController()
// Skip updates if the area is too big
const fetchBounds = map.getBounds()
const fetchArea = getLngLatBoundsSize(fetchBounds)
if (fetchArea > config.noteQueryAreaMaxSize) return
// Skip updates if the view is satisfied
if (fetchedBounds) {
const visibleBounds = getLngLatBoundsIntersection(fetchedBounds, fetchBounds)
const visibleArea = getLngLatBoundsSize(visibleBounds)
const proportion = visibleArea / Math.max(getLngLatBoundsSize(fetchedBounds), fetchArea)
if (proportion > reloadProportionThreshold) return
}
const [[minLon, minLat], [maxLon, maxLat]] = fetchBounds.adjustAntiMeridian().toArray()
fetch(`/api/web/note/map?bbox=${minLon},${minLat},${maxLon},${maxLat}`, {
method: "GET",
mode: "same-origin",
cache: "no-store", // request params are too volatile to cache
signal: abortController.signal,
priority: "high",
})
.then(async (resp) => {
if (!resp.ok) throw new Error(`${resp.status} ${resp.statusText}`)
const buffer = await resp.arrayBuffer()
const render = fromBinary(RenderNotesDataSchema, new Uint8Array(buffer))
const notes = convertRenderNotesData(render)
source.setData(renderObjects(notes))
fetchedBounds = fetchBounds
console.debug("Notes layer showing", notes.length, "notes")
})
.catch((error) => {
if (error.name === "AbortError") return
console.error("Failed to fetch notes", error)
source.setData(emptyFeatureCollection)
})
} | /** On map update, fetch the notes and update the notes layer */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_notes-layer.ts#L84-L128 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | updateState | const updateState = () => {
const zoom = map.getZoom()
if (zoom < queryFeaturesMinZoom) {
if (!button.disabled) {
if (button.classList.contains("active")) button.click()
button.blur()
button.disabled = true
Tooltip.getInstance(button).setContent({
".tooltip-inner": i18next.t("javascripts.site.queryfeature_disabled_tooltip"),
})
}
} else if (button.disabled) {
button.disabled = false
Tooltip.getInstance(button).setContent({
".tooltip-inner": i18next.t("javascripts.site.queryfeature_tooltip"),
})
}
} | /** On map zoom, change button availability */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_query-features.ts#L54-L71 | 42f2654614f20520271f46b3ddd389732dde6545 |
openstreetmap-ng | github_2023 | openstreetmap-ng | typescript | updateAvailableOverlays | const updateAvailableOverlays = () => {
// Skip updates if the sidebar is hidden
if (!button.classList.contains("active")) return
const currentViewAreaSize = getLngLatBoundsSize(map.getBounds())
for (const [layerId, areaMaxSize] of [
["notes", config.noteQueryAreaMaxSize],
["data", config.mapQueryAreaMaxSize],
] as [LayerId, number][]) {
const checkbox = layerIdOverlayCheckboxMap.get(layerId)
const isAvailable = currentViewAreaSize <= areaMaxSize
if (isAvailable) {
if (checkbox.disabled) {
checkbox.disabled = false
const parent = checkbox.closest(".form-check") as HTMLElement
parent.classList.remove("disabled")
parent.ariaDisabled = "false"
const tooltip = Tooltip.getInstance(parent)
tooltip.disable()
tooltip.hide()
// Restore the overlay state if it was checked before
if (checkbox.dataset.wasChecked) {
console.debug("Restoring checked state for overlay", layerId)
checkbox.dataset.wasChecked = undefined
checkbox.checked = true
checkbox.dispatchEvent(new Event("change"))
}
}
} else if (!checkbox.disabled) {
checkbox.blur()
checkbox.disabled = true
const parent = checkbox.closest(".form-check") as HTMLElement
parent.classList.add("disabled")
parent.ariaDisabled = "true"
Tooltip.getOrCreateInstance(parent, {
title: parent.dataset.bsTitle,
placement: "left",
}).enable()
// Force uncheck the overlay when it becomes unavailable
if (checkbox.checked) {
console.debug("Forcing unchecked state for overlay", layerId)
checkbox.dataset.wasChecked = "true"
checkbox.checked = false
checkbox.dispatchEvent(new Event("change"))
}
}
}
} | /** On map zoom, update the available overlays */ | https://github.com/openstreetmap-ng/openstreetmap-ng/blob/42f2654614f20520271f46b3ddd389732dde6545/app/static/ts/leaflet/_sidebar-layers.ts#L118-L170 | 42f2654614f20520271f46b3ddd389732dde6545 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.