prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
import { DisassembledInstruction } from "./types";
import { isLetterChar, maskOfSize } from "./util";
export const buildDisassembledInstructionString = (
{ instruction, actualWord, address }: DisassembledInstruction,
immediateLabel: string | undefined
) => {
let instructionString = instruction.originalInstruction;
if (instruction.type === "immediate") {
const { bitCount, stringIndex, stringLength } = instruction.immediate;
const immediatePrefix = instructionString.substring(0, stringIndex);
const immediateSuffix = instructionString.substring(
stringIndex + stringLength
);
let immediate = "";
if (immediateLabel) {
immediate = immediateLabel;
} else {
const argument = maskOfSize(bitCount) & actualWord;
if (isLetterChar(immediatePrefix.charAt(immediatePrefix.length - 1))) {
// If letter, treat as decimal
immediate = argument.toString();
} else {
// Otherwise, treat as hex
immediate = `0x${argument.toString(16).toUpperCase()}`;
}
}
instructionString = `${immediatePrefix}${immediate}${immediateSuffix}`;
}
// Separate out instruction so that it formats nicely
// Four total columns
// Opcode - Source - Dest - Comments
const splitInstruction = instructionString.split(/\s+/);
let lastPadWidth = 0;
for (let i = 2; i >= splitInstruction.length - 1; i--) {
lastPadWidth += columnPadWidth(i);
}
const formattedInstructionString = splitInstruction
| .map((s, i) => { |
const pad =
i === splitInstruction.length - 1 ? lastPadWidth : columnPadWidth(i);
return s.padEnd(pad);
})
.join("");
const comment = `// 0x${address
.toString(16)
.toUpperCase()
.padEnd(4)} (0x${actualWord.toString(16).toUpperCase()})`;
return `${formattedInstructionString.padEnd(81)}${comment}`;
};
const columnPadWidth = (column: number) => {
switch (column) {
case 0:
return 6;
case 1:
return 5;
case 2:
return 10;
}
return 0;
};
| src/lib/display.ts | agg23-tamagotchi-disassembled-421eacb | [
{
"filename": "src/lib/disassembly.ts",
"retrieved_chunk": " 8192\n );\n for (let i = 0; i < buffer.length; i += 2) {\n const highByte = buffer[i]!;\n const lowByte = buffer[i + 1]!;\n const address = i / 2;\n const correctedWord = (highByte << 8) | lowByte;\n const instruction = findWordInstruction(correctedWord, instructions);\n const disassembledInstruction: DisassembledInstruction = {\n instruction,",
"score": 32.6385783677338
},
{
"filename": "src/lib/opcodeOutput.ts",
"retrieved_chunk": "): Buffer => {\n const bufferSize = word16Align ? 8192 * 2 : (8192 * 3) / 2;\n const buffer = Buffer.alloc(bufferSize);\n let byteBuffer = 0;\n let bufferAddress = 0;\n let lowNibble = false;\n let evenByte = true;\n for (let i = 0; i < threeNibbleBuffer.length; i++) {\n const nibble = threeNibbleBuffer[i]!;\n const writeSpacerValue = word16Align && !lowNibble && evenByte;",
"score": 30.337544956587326
},
{
"filename": "src/lib/disassembly.ts",
"retrieved_chunk": "};\nconst findWordInstruction = (word: number, instructions: Instruction[]) => {\n // Naive because it doesn't really matter\n let bestMatch = instructions[0]!;\n for (let i = 0; i < instructions.length; i++) {\n const instruction = instructions[i]!;\n if (instruction.sortableOpcode <= word) {\n bestMatch = instruction;\n } else {\n // We've passed the best solution, end",
"score": 29.33204285253087
},
{
"filename": "src/lib/opcodeOutput.ts",
"retrieved_chunk": " let index = 0;\n let outputWord = 0;\n while (index < template.length) {\n const char = template[index];\n if (char === \"%\") {\n // Consume chars until whitespace\n let data = 0;\n let count = 0;\n for (let i = 1; i < Math.min(13, template.length - index); i++) {\n const nextChar = template[index + i]!;",
"score": 28.923054110029593
},
{
"filename": "src/extractIcons.ts",
"retrieved_chunk": " for (let i = 0; i < buffer.length; i += 2) {\n // Skip the low byte of every word\n const highNibble = buffer[i]! & 0xf;\n if (highNibble === 0x9) {\n // LBPX\n // This is probably a set of pixels for an image\n lbpxCount += 1;\n } else if (highNibble === 0x1 && lbpxCount > 0) {\n // RETD\n // We have some number of possible pixels, so consider this a complete image write",
"score": 26.21371821634414
}
] | typescript | .map((s, i) => { |
import { log } from "./log";
import { AssembledProgram, Option } from "./types";
import { maskOfSize } from "./util";
/**
* Builds the output buffer from the matched instructions
* @param program The configured program we have built
* @param word16Align If true, align the 12 bit opcodes to 16 bit words. The lowest nibble will be 0
* @returns The output buffer that should be written to the assembled binary
*/
export const outputInstructions = (
program: AssembledProgram,
word16Align: boolean
): Option<Buffer> => {
// This buffer stores each nibble of the program separately, and we will combine this later into the output buffer
const threeNibbleBuffer: number[] = new Array(8192 * 3);
// Fill array with 0xF
for (let i = 0; i < threeNibbleBuffer.length; i++) {
threeNibbleBuffer[i] = 0xf;
}
for (const instruction of program.matchedInstructions) {
let opcode = 0;
switch (instruction.type) {
case "literal": {
opcode = buildOpcode(instruction.opcodeString, 0, 0);
break;
}
case "immediate": {
opcode = buildOpcode(
instruction.opcodeString,
instruction.bitCount,
instruction.immediate
);
break;
}
case "label": {
const label = | program.matchedLabels[instruction.label]; |
if (!label) {
log(`Unknown label ${instruction.label}`, instruction.lineNumber);
return { type: "none" };
}
opcode = buildOpcode(
instruction.opcodeString,
instruction.bitCount,
label.address
);
break;
}
case "constant": {
if (instruction.subtype === "literal") {
opcode = instruction.value;
} else {
// Label
const label = program.matchedLabels[instruction.label];
if (!label) {
log(`Unknown label ${instruction.label}`, instruction.lineNumber);
return { type: "none" };
}
console.log(`${label.address.toString(16)}`);
opcode = label.address;
}
break;
}
}
const low = opcode & 0xf;
const mid = (opcode & 0xf0) >> 4;
const high = (opcode & 0xf00) >> 8;
const baseAddress = instruction.address * 3;
// We use reverse order because that's how the nibbles are in the ROM
threeNibbleBuffer[baseAddress] = high;
threeNibbleBuffer[baseAddress + 1] = mid;
threeNibbleBuffer[baseAddress + 2] = low;
}
return {
type: "some",
value: copyToOutputBuffer(threeNibbleBuffer, word16Align),
};
};
const copyToOutputBuffer = (
threeNibbleBuffer: number[],
word16Align: boolean
): Buffer => {
const bufferSize = word16Align ? 8192 * 2 : (8192 * 3) / 2;
const buffer = Buffer.alloc(bufferSize);
let byteBuffer = 0;
let bufferAddress = 0;
let lowNibble = false;
let evenByte = true;
for (let i = 0; i < threeNibbleBuffer.length; i++) {
const nibble = threeNibbleBuffer[i]!;
const writeSpacerValue = word16Align && !lowNibble && evenByte;
if (lowNibble || writeSpacerValue) {
// "Second", lower value of byte, or we're writing the spacer now
byteBuffer |= nibble;
buffer[bufferAddress] = byteBuffer;
bufferAddress += 1;
byteBuffer = 0;
evenByte = !evenByte;
} else {
// "First", upper value of byte
byteBuffer |= nibble << 4;
}
if (!writeSpacerValue) {
// We've moved to the next byte if we wrote a spacer, so stay at !lowNibble
lowNibble = !lowNibble;
}
}
return buffer;
};
/**
* Comsumes the opcode template from the BASS arch file and produces the actual output word
* @param template The opcode template from the BASS arch file
* @param argSize The number of bits in an argument to the opcode, if any
* @param argument The actual data to pass as an argument to the opcode, if any
* @returns The output opcode as a 12 bit word
*/
export const buildOpcode = (
template: string,
argSize: number,
argument: number
) => {
let index = 0;
let outputWord = 0;
while (index < template.length) {
const char = template[index];
if (char === "%") {
// Consume chars until whitespace
let data = 0;
let count = 0;
for (let i = 1; i < Math.min(13, template.length - index); i++) {
const nextChar = template[index + i]!;
if (nextChar !== "1" && nextChar !== "0") {
// Stop consuming
break;
}
data <<= 1;
data |= nextChar === "1" ? 1 : 0;
count += 1;
}
// Consume the next four chars as bits
outputWord <<= count;
outputWord |= data;
index += count + 1;
} else if (char === "=") {
if (template[index + 1] !== "a") {
console.log(
`ERROR: Unexpected char after = in instruction definition "${template}"`
);
return 0;
}
outputWord <<= argSize;
outputWord |= maskOfSize(argSize) & argument;
index += 2;
} else {
index += 1;
}
}
return outputWord;
};
| src/lib/opcodeOutput.ts | agg23-tamagotchi-disassembled-421eacb | [
{
"filename": "src/assembler.ts",
"retrieved_chunk": " program.matchedInstructions.push({\n type: \"label\",\n line,\n label: matches[2],\n opcodeString: instruction.opcodeString,\n bitCount: instruction.immediate.bitCount,\n lineNumber,\n address,\n });\n } else {",
"score": 22.83666190524091
},
{
"filename": "src/assembler.ts",
"retrieved_chunk": " program.currentAddress += 1;\n break;\n }\n }\n if (hasInstruction && program.unmatchedLabels.length > 0) {\n // Add queued labels\n for (const label of program.unmatchedLabels) {\n const existingLabel = program.matchedLabels[label.label];\n if (existingLabel) {\n log(",
"score": 18.115567476921743
},
{
"filename": "src/assembler.ts",
"retrieved_chunk": " return;\n }\n program.matchedInstructions.push({\n type: \"immediate\",\n line,\n immediate: parseNumber(matches[1]),\n opcodeString: instruction.opcodeString,\n bitCount: instruction.immediate.bitCount,\n lineNumber,\n address,",
"score": 15.303257339346818
},
{
"filename": "src/assembler.ts",
"retrieved_chunk": " // Instruction on this line, pair them up\n program.matchedLabels[label] = {\n lineNumber,\n instructionIndex: program.matchedInstructions.length - 1,\n address: program.currentAddress - 1,\n };\n } else {\n // Will pair with some future instruction. Queue it\n program.unmatchedLabels.push({\n label,",
"score": 14.568158121836623
},
{
"filename": "src/assembler.ts",
"retrieved_chunk": " `Label \"${label.label}\" already exists. Was created on line ${existingLabel.lineNumber}`,\n lineNumber\n );\n return;\n }\n program.matchedLabels[label.label] = {\n lineNumber,\n instructionIndex: program.matchedInstructions.length - 1,\n address: program.currentAddress - 1,\n };",
"score": 14.11598646679743
}
] | typescript | program.matchedLabels[instruction.label]; |
import { DisassembledInstruction } from "./types";
import { isLetterChar, maskOfSize } from "./util";
export const buildDisassembledInstructionString = (
{ instruction, actualWord, address }: DisassembledInstruction,
immediateLabel: string | undefined
) => {
let instructionString = instruction.originalInstruction;
if (instruction.type === "immediate") {
const { bitCount, stringIndex, stringLength } = instruction.immediate;
const immediatePrefix = instructionString.substring(0, stringIndex);
const immediateSuffix = instructionString.substring(
stringIndex + stringLength
);
let immediate = "";
if (immediateLabel) {
immediate = immediateLabel;
} else {
const argument = maskOfSize(bitCount) & actualWord;
if (isLetterChar(immediatePrefix.charAt(immediatePrefix.length - 1))) {
// If letter, treat as decimal
immediate = argument.toString();
} else {
// Otherwise, treat as hex
immediate = `0x${argument.toString(16).toUpperCase()}`;
}
}
instructionString = `${immediatePrefix}${immediate}${immediateSuffix}`;
}
// Separate out instruction so that it formats nicely
// Four total columns
// Opcode - Source - Dest - Comments
const splitInstruction = instructionString.split(/\s+/);
let lastPadWidth = 0;
for (let i = 2; i >= splitInstruction.length - 1; i--) {
lastPadWidth += columnPadWidth(i);
}
const formattedInstructionString = splitInstruction
.map(( | s, i) => { |
const pad =
i === splitInstruction.length - 1 ? lastPadWidth : columnPadWidth(i);
return s.padEnd(pad);
})
.join("");
const comment = `// 0x${address
.toString(16)
.toUpperCase()
.padEnd(4)} (0x${actualWord.toString(16).toUpperCase()})`;
return `${formattedInstructionString.padEnd(81)}${comment}`;
};
const columnPadWidth = (column: number) => {
switch (column) {
case 0:
return 6;
case 1:
return 5;
case 2:
return 10;
}
return 0;
};
| src/lib/display.ts | agg23-tamagotchi-disassembled-421eacb | [
{
"filename": "src/lib/disassembly.ts",
"retrieved_chunk": " 8192\n );\n for (let i = 0; i < buffer.length; i += 2) {\n const highByte = buffer[i]!;\n const lowByte = buffer[i + 1]!;\n const address = i / 2;\n const correctedWord = (highByte << 8) | lowByte;\n const instruction = findWordInstruction(correctedWord, instructions);\n const disassembledInstruction: DisassembledInstruction = {\n instruction,",
"score": 31.687472349835627
},
{
"filename": "src/lib/opcodeOutput.ts",
"retrieved_chunk": "): Buffer => {\n const bufferSize = word16Align ? 8192 * 2 : (8192 * 3) / 2;\n const buffer = Buffer.alloc(bufferSize);\n let byteBuffer = 0;\n let bufferAddress = 0;\n let lowNibble = false;\n let evenByte = true;\n for (let i = 0; i < threeNibbleBuffer.length; i++) {\n const nibble = threeNibbleBuffer[i]!;\n const writeSpacerValue = word16Align && !lowNibble && evenByte;",
"score": 30.337544956587326
},
{
"filename": "src/lib/opcodeOutput.ts",
"retrieved_chunk": " let index = 0;\n let outputWord = 0;\n while (index < template.length) {\n const char = template[index];\n if (char === \"%\") {\n // Consume chars until whitespace\n let data = 0;\n let count = 0;\n for (let i = 1; i < Math.min(13, template.length - index); i++) {\n const nextChar = template[index + i]!;",
"score": 28.923054110029593
},
{
"filename": "src/lib/disassembly.ts",
"retrieved_chunk": "};\nconst findWordInstruction = (word: number, instructions: Instruction[]) => {\n // Naive because it doesn't really matter\n let bestMatch = instructions[0]!;\n for (let i = 0; i < instructions.length; i++) {\n const instruction = instructions[i]!;\n if (instruction.sortableOpcode <= word) {\n bestMatch = instruction;\n } else {\n // We've passed the best solution, end",
"score": 25.81040250225652
},
{
"filename": "src/extractIcons.ts",
"retrieved_chunk": " for (let i = 0; i < buffer.length; i += 2) {\n // Skip the low byte of every word\n const highNibble = buffer[i]! & 0xf;\n if (highNibble === 0x9) {\n // LBPX\n // This is probably a set of pixels for an image\n lbpxCount += 1;\n } else if (highNibble === 0x1 && lbpxCount > 0) {\n // RETD\n // We have some number of possible pixels, so consider this a complete image write",
"score": 23.940133111362258
}
] | typescript | s, i) => { |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) irotation: f32,
@location(4) isize: f32,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
fn rotate(rad: f32) -> mat2x2<f32> {
var c: f32 = cos(rad);
var s: f32 = sin(rad);
return mat2x2<f32>(c, s, -s, c);
}
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1);
return out;
}
`;
const Fragment = /* wgsl */`
@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(vec3(0.125), 1);
}
`;
class Lines {
private readonly bindings: GPUBindGroup;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
this.geometry = Plane(device);
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 3,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 3 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{ format }],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: | { buffer: camera.getBuffer() },
},
],
}); |
this.simulation = simulation;
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { lines } = simulation.getBuffers();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, lines, 16);
pass.drawIndirect(lines, 0);
}
}
export default Lines;
| src/render/lines.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/points.ts",
"retrieved_chunk": " size: [512, 512],\n usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,\n });\n this.bindings = device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: camera.getBuffer() },\n },",
"score": 29.421647540514705
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " });\n this.bindings = {\n data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: data },\n },\n {",
"score": 28.56924017075588
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: joints },\n },\n {\n binding: 1,\n resource: { buffer: lines },",
"score": 26.6065370667046
},
{
"filename": "src/compute/simulation/constrain.ts",
"retrieved_chunk": " ],\n }),\n points: points.map((buffer) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [\n {\n binding: 0,\n resource: { buffer },\n },\n ],",
"score": 25.96432034845914
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " },\n {\n binding: 2,\n resource: { buffer: uniforms },\n },\n ],\n }),\n points: points.map((buffer) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [",
"score": 25.046734802807382
}
] | typescript | { buffer: camera.getBuffer() },
},
],
}); |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) irotation: f32,
@location(4) isize: f32,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
fn rotate(rad: f32) -> mat2x2<f32> {
var c: f32 = cos(rad);
var s: f32 = sin(rad);
return mat2x2<f32>(c, s, -s, c);
}
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1);
return out;
}
`;
const Fragment = /* wgsl */`
@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(vec3(0.125), 1);
}
`;
class Lines {
private readonly bindings: GPUBindGroup;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
this. | geometry = Plane(device); |
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 3,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 3 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{ format }],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: { buffer: camera.getBuffer() },
},
],
});
this.simulation = simulation;
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { lines } = simulation.getBuffers();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, lines, 16);
pass.drawIndirect(lines, 0);
}
}
export default Lines;
| src/render/lines.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/points.ts",
"retrieved_chunk": " device: GPUDevice,\n format: GPUTextureFormat,\n samples: number,\n simulation: Simulation,\n ) {\n this.device = device;\n this.geometry = Plane(device, 2, 2);\n this.pipeline = device.createRenderPipeline({\n layout: 'auto',\n vertex: {",
"score": 35.00819367526398
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": "`;\nclass Points {\n private readonly bindings: GPUBindGroup;\n private readonly device: GPUDevice;\n private readonly geometry: GPUBuffer;\n private readonly pipeline: GPURenderPipeline;\n private readonly simulation: Simulation;\n private readonly texture: GPUTexture;\n constructor(\n camera: Camera,",
"score": 30.92861333846494
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " private readonly descriptor: GPURenderPassDescriptor;\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];\n private readonly samples: number = 4;\n private target: GPUTexture = undefined as unknown as GPUTexture;\n constructor(camera: Camera, device: GPUDevice) {\n this.camera = camera;\n this.canvas = document.createElement('canvas');\n const context = this.canvas.getContext('webgpu');",
"score": 24.592385571659506
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": "import Camera from './camera';\nimport { Plane } from './geometry';\nimport Simulation from '../compute/simulation';\nconst Vertex = /* wgsl */`\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) uv: vec2<f32>,\n @location(2) iposition: vec2<f32>,\n @location(3) isize: f32,\n @location(4) iuv: vec2<f32>,",
"score": 18.117756282554183
},
{
"filename": "src/main.ts",
"retrieved_chunk": " if (!dom) {\n throw new Error(\"Couldn't get app DOM node\");\n }\n const camera = new Camera(device);\n const renderer = new Renderer(camera, device);\n const input = new Input(renderer.getCanvas());\n const simulation = new Simulation(device);\n dom.appendChild(renderer.getCanvas());\n renderer.setAnimationLoop((command, delta) => (\n simulation.compute(command, delta, input.getPointer(camera), camera.getZoom() * 0.02)",
"score": 15.862627131933667
}
] | typescript | geometry = Plane(device); |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) irotation: f32,
@location(4) isize: f32,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
fn rotate(rad: f32) -> mat2x2<f32> {
var c: f32 = cos(rad);
var s: f32 = sin(rad);
return mat2x2<f32>(c, s, -s, c);
}
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1);
return out;
}
`;
const Fragment = /* wgsl */`
@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(vec3(0.125), 1);
}
`;
class Lines {
private readonly bindings: GPUBindGroup;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
this.geometry = Plane(device);
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 3,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 3 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{ format }],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: { buffer: camera.getBuffer() },
},
],
});
this.simulation = simulation;
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { | lines } = simulation.getBuffers(); |
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, lines, 16);
pass.drawIndirect(lines, 0);
}
}
export default Lines;
| src/render/lines.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/points.ts",
"retrieved_chunk": " this.simulation = simulation;\n this.generateDefaultTexture();\n }\n render(pass: GPURenderPassEncoder) {\n const { bindings, geometry, pipeline, simulation } = this;\n const { count, data, points } = simulation.getBuffers();\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings);\n pass.setVertexBuffer(0, geometry);\n pass.setVertexBuffer(1, points);",
"score": 43.52587846857771
},
{
"filename": "src/main.ts",
"retrieved_chunk": " ));\n renderer.setSize(window.innerWidth, window.innerHeight);\n simulation.load(Cloth());\n const lines = new Lines(camera, device, renderer.getFormat(), renderer.getSamples(), simulation);\n renderer.add(lines);\n const points = new Points(camera, device, renderer.getFormat(), renderer.getSamples(), simulation);\n renderer.add(points);\n input.setHotkeys({\n 1: () => simulation.load(Cloth()),\n 2: () => simulation.load(Cloth(false, true)),",
"score": 22.766639102605865
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": "`;\nclass Points {\n private readonly bindings: GPUBindGroup;\n private readonly device: GPUDevice;\n private readonly geometry: GPUBuffer;\n private readonly pipeline: GPURenderPipeline;\n private readonly simulation: Simulation;\n private readonly texture: GPUTexture;\n constructor(\n camera: Camera,",
"score": 19.30196054729442
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " device: GPUDevice,\n format: GPUTextureFormat,\n samples: number,\n simulation: Simulation,\n ) {\n this.device = device;\n this.geometry = Plane(device, 2, 2);\n this.pipeline = device.createRenderPipeline({\n layout: 'auto',\n vertex: {",
"score": 17.40066019722838
},
{
"filename": "src/main.ts",
"retrieved_chunk": " 3: () => simulation.load(Ropes()),\n 4: () => simulation.load(Cloth(true, false)),\n 5: () => simulation.load(Cloth(true, true)),\n escape: () => simulation.reset(),\n '?': () => document.getElementById('help')?.classList.toggle('hidden'), \n });\n window.addEventListener('drop', (e) => {\n e.preventDefault();\n const [file] = e.dataTransfer?.files || [];\n if (file && file.type.indexOf('image/') === 0) {",
"score": 17.284070864365333
}
] | typescript | lines } = simulation.getBuffers(); |
import { Joint, JointBuffer, Point, PointBuffers } from '../simulation/types';
export default (large: boolean = false, tension: boolean = false) => {
const width = large ? 65 : 33;
const height = large ? 65 : 33;
const gap = 4;
const points: Point[] = [];
const joints: Joint[] = [];
for (let i = 0, y = 0; y < height; y++) {
for (let x = 0; x < width; x++, i++) {
points.push({
locked: tension ? (
((y === 0 || y === height - 1) && (x % 8 === 0))
|| ((x === 0 || x === width - 1) && (y % 8 === 0))
) : (
y === height - 1 && (x % 8 === 0)
),
position: {
x: (x - width * 0.5 + 0.5) * gap * 1.125 + gap * (Math.random() - 0.25) * 0.125,
y: (y - height * 0.5 + 0.5) * gap + gap * (Math.random() - 0.5) * 0.125 + height * gap * 0.2,
},
size: 1.5 + Math.random() * 0.5,
uv: {
x: (x + 0.5) / width,
y: (y + 0.5) / height,
},
});
if (x < width - 1) {
joints.push({
enabled: true,
a: i,
b: i + 1,
length: 0,
});
}
if (y > 0) {
joints.push({
enabled: true,
a: i,
b: i - width,
length: 0,
});
}
}
}
joints.forEach((joint) => {
const a = points | [joint.a].position; |
const b = points[joint.b].position;
joint.length = Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
});
if (tension || large) {
points.forEach(({ position }) => {
if (tension) position.x *= 1.25;
position.y = (position.y - height * gap * 0.2) * 1.4;
});
}
return {
...PointBuffers(points),
joints: JointBuffer(joints),
numJoints: joints.length,
numPoints: points.length,
};
}
| src/compute/generation/cloth.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/compute/simulation/constrain.ts",
"retrieved_chunk": "fn main() {\n lines.instanceCount = 0;\n for (var j: u32 = 0; j < ${numIterations}; j++) {\n for (var i: u32 = 0; i < ${numJoints}; i++) {\n var joint = joints[i];\n if (joint.enabled == 0) {\n continue;\n }\n var origin = (points[joint.a] + points[joint.b]) * 0.5;\n var edge = normalize(points[joint.a] - points[joint.b]) * joint.length * 0.5;",
"score": 35.035155386584805
},
{
"filename": "src/compute/simulation/constrain.ts",
"retrieved_chunk": " if (data[joint.a].locked == 0) {\n points[joint.a] = origin + edge;\n }\n if (data[joint.b].locked == 0) {\n points[joint.b] = origin - edge;\n }\n }\n }\n}\n`;",
"score": 28.61232204813358
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " return;\n }\n }\n var origin = (points[joint.a] + points[joint.b]) * 0.5;\n var line = points[joint.a] - points[joint.b];\n var direction = normalize(line);\n var rotation = atan2(direction.x, direction.y);\n var size = length(line);\n var instance = atomicAdd(&lines.instanceCount, 1);\n lines.data[instance].position = origin;",
"score": 26.68786655838229
},
{
"filename": "src/compute/generation/ropes.ts",
"retrieved_chunk": " });\n if (i >= 3 && i < length - 1) {\n joints.push({\n enabled: true,\n a: o + i,\n b: o + i + 1,\n length: 4,\n });\n }\n }",
"score": 26.012464552419345
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " }\n var joint = joints[index];\n if (joint.enabled == 0) {\n return;\n }\n if (uniforms.button == 2) {\n if (\n sdSegment(uniforms.pointer, points[joint.a], points[joint.b]) <= uniforms.radius * 0.25\n ) {\n joints[index].enabled = 0;",
"score": 24.85173570839826
}
] | typescript | [joint.a].position; |
import ConstrainSimulation from './constrain';
import ComputeLines from './lines';
import StepSimulation from './step';
import { LineBuffer, UniformsBuffer } from './types';
class Simulation {
private buffers?: {
data: GPUBuffer;
joints: GPUBuffer;
lines: GPUBuffer;
points: GPUBuffer[];
};
private count: number = 0;
private device: GPUDevice;
private initial?: {
joints: ArrayBuffer;
points: ArrayBuffer;
};
private pipelines?: {
constraint: ConstrainSimulation,
lines: ComputeLines,
step: StepSimulation,
};
private step: number = 0;
private readonly uniforms: UniformsBuffer;
constructor(device: GPUDevice) {
this.device = device;
this.uniforms = new UniformsBuffer(device);
}
compute(
command: GPUCommandEncoder,
delta: number,
pointer: { button: number; position: [number, number] | Float32Array; },
radius: number
) {
const { buffers, pipelines, step, uniforms } = this;
if (!buffers || !pipelines) {
return;
}
uniforms.delta = delta;
uniforms.button = pointer.button;
uniforms.pointer = pointer.position;
uniforms.radius = radius;
uniforms.update();
const pass = command.beginComputePass();
pipelines. | step.compute(pass, step); |
this.step = (this.step + 1) % 2;
pipelines.constraint.compute(pass, this.step);
pipelines.lines.compute(pass, this.step);
pass.end();
}
getBuffers() {
const { buffers, count, step } = this;
if (!buffers) {
throw new Error("Simulation is not loaded");
}
return {
count,
data: buffers.data,
lines: buffers.lines,
points: buffers.points[step],
};
}
load(
{ data, joints, numJoints, points, numPoints }: {
data: ArrayBuffer;
joints: ArrayBuffer;
numJoints: number;
points: ArrayBuffer;
numPoints: number;
}
) {
const { device } = this;
const createBuffer = (data: ArrayBuffer, usage: number) => {
const buffer = device.createBuffer({
mappedAtCreation: true,
size: data.byteLength,
usage,
});
new Uint32Array(buffer.getMappedRange()).set(new Uint32Array(data));
buffer.unmap();
return buffer;
};
if (this.buffers) {
this.buffers.data.destroy();
this.buffers.joints.destroy();
this.buffers.lines.destroy();
this.buffers.points.forEach((buffer) => buffer.destroy());
}
this.buffers = {
data: createBuffer(
data,
GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX
),
joints: createBuffer(
joints,
GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE
),
lines: LineBuffer(device, numJoints),
points: Array.from({ length: 2 }, () => createBuffer(
points,
GPUBufferUsage.COPY_DST
| GPUBufferUsage.STORAGE
| GPUBufferUsage.VERTEX
)),
};
this.count = numPoints;
this.initial = { joints, points };
this.pipelines = {
constraint: new ConstrainSimulation(
device,
this.buffers.data,
this.buffers.joints,
numJoints,
this.buffers.lines,
this.buffers.points,
numPoints
),
lines: new ComputeLines(
device,
this.buffers.joints,
numJoints,
this.buffers.lines,
this.buffers.points,
numPoints,
this.uniforms.getBuffer()
),
step: new StepSimulation(
device,
this.buffers.data,
this.buffers.points,
numPoints,
this.uniforms.getBuffer()
),
};
}
reset() {
const { buffers, device, initial } = this;
if (!buffers || !initial) {
return;
}
device.queue.writeBuffer(buffers.joints, 0, initial.joints);
buffers.points.forEach((buffer) => (
device.queue.writeBuffer(buffer, 0, initial.points)
));
}
}
export default Simulation;
| src/compute/simulation/index.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " }\n var joint = joints[index];\n if (joint.enabled == 0) {\n return;\n }\n if (uniforms.button == 2) {\n if (\n sdSegment(uniforms.pointer, points[joint.a], points[joint.b]) <= uniforms.radius * 0.25\n ) {\n joints[index].enabled = 0;",
"score": 40.85177338610576
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " if (length(d) < min(uniforms.radius * 4, 24)) {\n point += d * uniforms.radius * uniforms.delta;\n }\n }\n }\n output[index] = point;\n}\n`;\nclass StepSimulation {\n private readonly bindings: {",
"score": 39.071055201806004
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " let index: u32 = id.x;\n if (index >= ${numPoints}) {\n return;\n }\n var point = input[index];\n if (data[index].locked == 0) {\n point += point - output[index];\n point += vec2<f32>(0, -8) * uniforms.delta;\n if (uniforms.button != 2) {\n var d = point - uniforms.pointer;",
"score": 36.60129247066449
},
{
"filename": "src/compute/simulation/types.ts",
"retrieved_chunk": "struct Uniforms {\n button: u32,\n delta: f32,\n pointer: vec2<f32>,\n radius: f32,\n}\n`;\nexport class UniformsBuffer {\n private readonly buffers: {\n cpu: ArrayBuffer,",
"score": 28.930706875674502
},
{
"filename": "src/compute/input.ts",
"retrieved_chunk": " const { pointer } = this;\n if (pointer.id !== pointerId) {\n return;\n }\n pointer.id = -1;\n pointer.button = 0;\n }\n}\nexport default Input;",
"score": 23.135753903405053
}
] | typescript | step.compute(pass, step); |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) isize: f32,
@location(4) iuv: vec2<f32>,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) size: f32,
@location(1) uv: vec2<f32>,
@location(2) uv2: vec2<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vertex.isize + vertex.iposition, 0, 1);
out.size = vertex.isize;
out.uv = (vertex.uv - 0.5) * 2;
out.uv2 = vertex.iuv;
return out;
}
`;
const Fragment = /* wgsl */`
struct FragmentInput {
@location(0) size: f32,
@location(1) uv: vec2<f32>,
@location(2) uv2: vec2<f32>,
}
@group(0) @binding(1) var texture: texture_2d<f32>;
@group(0) @binding(2) var textureSampler: sampler;
fn linearTosRGB(linear: vec3<f32>) -> vec3<f32> {
if (all(linear <= vec3<f32>(0.0031308))) {
return linear * 12.92;
}
return (pow(abs(linear), vec3<f32>(1.0/2.4)) * 1.055) - vec3<f32>(0.055);
}
@fragment
fn main(fragment: FragmentInput) -> @location(0) vec4<f32> {
let l = min(length(fragment.uv), 1);
var uv = fragment.uv2 + (fragment.uv / fragment.size / 33);
return vec4<f32>(linearTosRGB(
textureSample(texture, textureSampler, uv).xyz + smoothstep(0.5, 1, l) * 0.1
), smoothstep(1, 0.8, l));
}
`;
class Points {
private readonly bindings: GPUBindGroup;
private readonly device: GPUDevice;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
private readonly texture: GPUTexture;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
this.device = device;
| this.geometry = Plane(device, 2, 2); |
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 3,
offset: 1 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{
format,
blend: {
color: {
srcFactor: 'src-alpha',
dstFactor: 'one-minus-src-alpha',
operation: 'add',
},
alpha: {
srcFactor: 'src-alpha',
dstFactor: 'one-minus-src-alpha',
operation: 'add',
},
},
}],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.texture = device.createTexture({
dimension: '2d',
format: 'rgba8unorm-srgb',
size: [512, 512],
usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: { buffer: camera.getBuffer() },
},
{
binding: 1,
resource: this.texture.createView(),
},
{
binding: 2,
resource: device.createSampler({ minFilter: 'linear', magFilter: 'linear' }),
},
],
});
this.simulation = simulation;
this.generateDefaultTexture();
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { count, data, points } = simulation.getBuffers();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, points);
pass.setVertexBuffer(2, data);
pass.draw(6, count, 0, 0);
}
setTexture(file: Blob) {
const image = new Image();
image.addEventListener('load', () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
let x = 0;
let y = 0;
let w = canvas.width = 512;
let h = canvas.height = 512;
if (image.width / image.height > w / h) {
w = image.width * canvas.height / image.height;
x = (canvas.width - w) * 0.5;
} else {
h = image.height * canvas.width / image.width;
y = (canvas.height - h) * 0.5;
}
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h);
this.updateTexture(canvas);
});
image.src = URL.createObjectURL(file);
}
private generateDefaultTexture() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
canvas.width = canvas.height = 512;
for (let i = 0; i < 256; i++) {
ctx.fillStyle = `hsl(${360 * Math.random()},${20 + 40 * Math.random()}%,${20 + 40 * Math.random()}%)`;
ctx.beginPath();
ctx.arc(canvas.width * Math.random(), canvas.height * Math.random(), 16 + Math.random() * 64, 0, Math.PI * 2);
ctx.fill();
}
this.updateTexture(canvas);
}
private async updateTexture(canvas: HTMLCanvasElement) {
const { device, texture } = this;
const source = await createImageBitmap(canvas)
device.queue.copyExternalImageToTexture({ source, flipY: true }, { texture }, [512, 512]);
}
}
export default Points;
| src/render/points.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/lines.ts",
"retrieved_chunk": " device: GPUDevice,\n format: GPUTextureFormat,\n samples: number,\n simulation: Simulation,\n ) {\n this.geometry = Plane(device);\n this.pipeline = device.createRenderPipeline({\n layout: 'auto',\n vertex: {\n buffers: [",
"score": 32.1763266288017
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " private readonly descriptor: GPURenderPassDescriptor;\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];\n private readonly samples: number = 4;\n private target: GPUTexture = undefined as unknown as GPUTexture;\n constructor(camera: Camera, device: GPUDevice) {\n this.camera = camera;\n this.canvas = document.createElement('canvas');\n const context = this.canvas.getContext('webgpu');",
"score": 30.229874045511952
},
{
"filename": "src/render/lines.ts",
"retrieved_chunk": " return vec4<f32>(vec3(0.125), 1);\n}\n`;\nclass Lines {\n private readonly bindings: GPUBindGroup;\n private readonly geometry: GPUBuffer;\n private readonly pipeline: GPURenderPipeline;\n private readonly simulation: Simulation;\n constructor(\n camera: Camera,",
"score": 21.15940724859176
},
{
"filename": "src/render/lines.ts",
"retrieved_chunk": "import Camera from './camera';\nimport { Plane } from './geometry';\nimport Simulation from '../compute/simulation';\nconst Vertex = /* wgsl */`\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) uv: vec2<f32>,\n @location(2) iposition: vec2<f32>,\n @location(3) irotation: f32,\n @location(4) isize: f32,",
"score": 15.729438783834041
},
{
"filename": "src/compute/simulation/index.ts",
"retrieved_chunk": " step: StepSimulation,\n };\n private step: number = 0;\n private readonly uniforms: UniformsBuffer;\n constructor(device: GPUDevice) {\n this.device = device;\n this.uniforms = new UniformsBuffer(device);\n }\n compute(\n command: GPUCommandEncoder,",
"score": 15.199828276975833
}
] | typescript | this.geometry = Plane(device, 2, 2); |
import { vec2 } from 'gl-matrix';
import Camera from '../render/camera';
class Input {
private hotkeys: Record<string, () => void> = {};
private readonly pointer: {
id: number;
button: number;
normalized: vec2;
position: vec2;
};
constructor(target: HTMLCanvasElement) {
this.pointer = {
id: -1,
button: 0,
normalized: vec2.fromValues(-1, -1),
position: vec2.create(),
};
window.addEventListener('keydown', this.onKeyDown.bind(this));
target.addEventListener('pointerdown', this.onPointerDown.bind(this));
window.addEventListener('pointermove', this.onPointerMove.bind(this));
target.addEventListener('pointerup', this.onPointerUp.bind(this));
{
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
canvas.width = 20;
canvas.height = 20;
ctx.lineWidth = 5;
ctx.strokeStyle = '#111';
ctx.arc(canvas.width * 0.5, canvas.height * 0.5, 6, 0, Math.PI * 2);
ctx.stroke();
ctx.lineWidth = 3;
ctx.strokeStyle = '#eee';
ctx.stroke();
canvas.toBlob((blob) => {
if (blob) {
document.body.style.cursor = `url(${URL.createObjectURL(blob)}) 10 10, default`;
}
});
}
}
getPointer(camera: | Camera) { |
const { pointer } = this;
vec2.transformMat4(
pointer.position,
pointer.normalized,
camera.getMatrixInverse()
);
return pointer;
}
setHotkeys(hotkeys: Record<string, () => void>) {
this.hotkeys = hotkeys;
}
private onKeyDown({ key, repeat, target }: KeyboardEvent) {
const { hotkeys } = this;
const handler = hotkeys[key.toLowerCase()];
if (
handler
&& !repeat
&& !['input', 'textarea', 'select'].includes(
(target as HTMLElement).tagName.toLowerCase()
)
) {
handler();
}
}
private onPointerDown({ buttons, pointerId, target }: PointerEvent) {
(target as HTMLCanvasElement).setPointerCapture(pointerId);
const { pointer } = this;
if (pointer.id !== -1) {
return;
}
pointer.id = pointerId;
pointer.button = buttons;
}
private onPointerMove({ pointerId, clientX, clientY }: PointerEvent) {
const { pointer } = this;
if (pointer.id !== -1 && pointer.id !== pointerId) {
return;
}
vec2.set(
pointer.normalized,
(clientX / window.innerWidth) * 2 - 1,
-(clientY / window.innerHeight) * 2 + 1
);
}
private onPointerUp({ pointerId, target }: PointerEvent) {
(target as HTMLCanvasElement).releasePointerCapture(pointerId);
const { pointer } = this;
if (pointer.id !== pointerId) {
return;
}
pointer.id = -1;
pointer.button = 0;
}
}
export default Input;
| src/compute/input.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/points.ts",
"retrieved_chunk": " y = (canvas.height - h) * 0.5;\n }\n ctx.imageSmoothingEnabled = true;\n ctx.imageSmoothingQuality = 'high';\n ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h);\n this.updateTexture(canvas);\n });\n image.src = URL.createObjectURL(file);\n }\n private generateDefaultTexture() {",
"score": 16.79468759797453
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " target,\n } = this;\n const pixelRatio = window.devicePixelRatio || 1;\n const size = [Math.floor(width * pixelRatio), Math.floor(height * pixelRatio)];\n canvas.width = size[0];\n canvas.height = size[1];\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n camera.setAspect(width / height);\n if (target) {",
"score": 12.571386306396212
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");\n }\n canvas.width = canvas.height = 512;\n for (let i = 0; i < 256; i++) {\n ctx.fillStyle = `hsl(${360 * Math.random()},${20 + 40 * Math.random()}%,${20 + 40 * Math.random()}%)`;\n ctx.beginPath();\n ctx.arc(canvas.width * Math.random(), canvas.height * Math.random(), 16 + Math.random() * 64, 0, Math.PI * 2);",
"score": 12.22417978836503
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " pass.setVertexBuffer(2, data);\n pass.draw(6, count, 0, 0);\n }\n setTexture(file: Blob) {\n const image = new Image();\n image.addEventListener('load', () => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");",
"score": 11.469648706418397
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " private readonly descriptor: GPURenderPassDescriptor;\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];\n private readonly samples: number = 4;\n private target: GPUTexture = undefined as unknown as GPUTexture;\n constructor(camera: Camera, device: GPUDevice) {\n this.camera = camera;\n this.canvas = document.createElement('canvas');\n const context = this.canvas.getContext('webgpu');",
"score": 9.887039673212396
}
] | typescript | Camera) { |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) irotation: f32,
@location(4) isize: f32,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
fn rotate(rad: f32) -> mat2x2<f32> {
var c: f32 = cos(rad);
var s: f32 = sin(rad);
return mat2x2<f32>(c, s, -s, c);
}
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1);
return out;
}
`;
const Fragment = /* wgsl */`
@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(vec3(0.125), 1);
}
`;
class Lines {
private readonly bindings: GPUBindGroup;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
| this.geometry = Plane(device); |
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 3,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 3 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{ format }],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: { buffer: camera.getBuffer() },
},
],
});
this.simulation = simulation;
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { lines } = simulation.getBuffers();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, lines, 16);
pass.drawIndirect(lines, 0);
}
}
export default Lines;
| src/render/lines.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/points.ts",
"retrieved_chunk": "`;\nclass Points {\n private readonly bindings: GPUBindGroup;\n private readonly device: GPUDevice;\n private readonly geometry: GPUBuffer;\n private readonly pipeline: GPURenderPipeline;\n private readonly simulation: Simulation;\n private readonly texture: GPUTexture;\n constructor(\n camera: Camera,",
"score": 44.22325209636002
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " device: GPUDevice,\n format: GPUTextureFormat,\n samples: number,\n simulation: Simulation,\n ) {\n this.device = device;\n this.geometry = Plane(device, 2, 2);\n this.pipeline = device.createRenderPipeline({\n layout: 'auto',\n vertex: {",
"score": 36.93124090748263
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " private readonly descriptor: GPURenderPassDescriptor;\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];\n private readonly samples: number = 4;\n private target: GPUTexture = undefined as unknown as GPUTexture;\n constructor(camera: Camera, device: GPUDevice) {\n this.camera = camera;\n this.canvas = document.createElement('canvas');\n const context = this.canvas.getContext('webgpu');",
"score": 30.712118639725304
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " data: GPUBindGroup,\n points: GPUBindGroup[],\n };\n private readonly pipeline: GPUComputePipeline;\n private readonly workgroups: number;\n constructor(\n device: GPUDevice,\n data: GPUBuffer,\n points: GPUBuffer[],\n numPoints: number,",
"score": 21.58089980456784
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": "import Camera from './camera';\nclass Renderer {\n private readonly animation: {\n clock: number;\n loop: (command: GPUCommandEncoder, delta: number, time: number) => void;\n request: number;\n };\n private readonly camera: Camera;\n private readonly canvas: HTMLCanvasElement;\n private readonly context: GPUCanvasContext;",
"score": 20.86563335558539
}
] | typescript | this.geometry = Plane(device); |
import { vec2 } from 'gl-matrix';
import Camera from '../render/camera';
class Input {
private hotkeys: Record<string, () => void> = {};
private readonly pointer: {
id: number;
button: number;
normalized: vec2;
position: vec2;
};
constructor(target: HTMLCanvasElement) {
this.pointer = {
id: -1,
button: 0,
normalized: vec2.fromValues(-1, -1),
position: vec2.create(),
};
window.addEventListener('keydown', this.onKeyDown.bind(this));
target.addEventListener('pointerdown', this.onPointerDown.bind(this));
window.addEventListener('pointermove', this.onPointerMove.bind(this));
target.addEventListener('pointerup', this.onPointerUp.bind(this));
{
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
canvas.width = 20;
canvas.height = 20;
ctx.lineWidth = 5;
ctx.strokeStyle = '#111';
ctx.arc(canvas.width * 0.5, canvas.height * 0.5, 6, 0, Math.PI * 2);
ctx.stroke();
ctx.lineWidth = 3;
ctx.strokeStyle = '#eee';
ctx.stroke();
canvas.toBlob((blob) => {
if (blob) {
document.body.style.cursor = `url(${URL.createObjectURL(blob)}) 10 10, default`;
}
});
}
}
getPointer(camera: Camera) {
const { pointer } = this;
vec2.transformMat4(
pointer.position,
pointer.normalized,
| camera.getMatrixInverse()
); |
return pointer;
}
setHotkeys(hotkeys: Record<string, () => void>) {
this.hotkeys = hotkeys;
}
private onKeyDown({ key, repeat, target }: KeyboardEvent) {
const { hotkeys } = this;
const handler = hotkeys[key.toLowerCase()];
if (
handler
&& !repeat
&& !['input', 'textarea', 'select'].includes(
(target as HTMLElement).tagName.toLowerCase()
)
) {
handler();
}
}
private onPointerDown({ buttons, pointerId, target }: PointerEvent) {
(target as HTMLCanvasElement).setPointerCapture(pointerId);
const { pointer } = this;
if (pointer.id !== -1) {
return;
}
pointer.id = pointerId;
pointer.button = buttons;
}
private onPointerMove({ pointerId, clientX, clientY }: PointerEvent) {
const { pointer } = this;
if (pointer.id !== -1 && pointer.id !== pointerId) {
return;
}
vec2.set(
pointer.normalized,
(clientX / window.innerWidth) * 2 - 1,
-(clientY / window.innerHeight) * 2 + 1
);
}
private onPointerUp({ pointerId, target }: PointerEvent) {
(target as HTMLCanvasElement).releasePointerCapture(pointerId);
const { pointer } = this;
if (pointer.id !== pointerId) {
return;
}
pointer.id = -1;
pointer.button = 0;
}
}
export default Input;
| src/compute/input.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/compute/simulation/index.ts",
"retrieved_chunk": " delta: number,\n pointer: { button: number; position: [number, number] | Float32Array; },\n radius: number\n ) {\n const { buffers, pipelines, step, uniforms } = this;\n if (!buffers || !pipelines) {\n return;\n }\n uniforms.delta = delta;\n uniforms.button = pointer.button;",
"score": 15.763704061662732
},
{
"filename": "src/compute/simulation/index.ts",
"retrieved_chunk": " uniforms.pointer = pointer.position;\n uniforms.radius = radius;\n uniforms.update();\n const pass = command.beginComputePass();\n pipelines.step.compute(pass, step);\n this.step = (this.step + 1) % 2;\n pipelines.constraint.compute(pass, this.step);\n pipelines.lines.compute(pass, this.step);\n pass.end();\n }",
"score": 14.429962716578238
},
{
"filename": "src/compute/simulation/types.ts",
"retrieved_chunk": "struct Uniforms {\n button: u32,\n delta: f32,\n pointer: vec2<f32>,\n radius: f32,\n}\n`;\nexport class UniformsBuffer {\n private readonly buffers: {\n cpu: ArrayBuffer,",
"score": 13.008405791911743
},
{
"filename": "src/main.ts",
"retrieved_chunk": " if (!dom) {\n throw new Error(\"Couldn't get app DOM node\");\n }\n const camera = new Camera(device);\n const renderer = new Renderer(camera, device);\n const input = new Input(renderer.getCanvas());\n const simulation = new Simulation(device);\n dom.appendChild(renderer.getCanvas());\n renderer.setAnimationLoop((command, delta) => (\n simulation.compute(command, delta, input.getPointer(camera), camera.getZoom() * 0.02)",
"score": 11.826353614770854
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": "import Camera from './camera';\nimport { Plane } from './geometry';\nimport Simulation from '../compute/simulation';\nconst Vertex = /* wgsl */`\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) uv: vec2<f32>,\n @location(2) iposition: vec2<f32>,\n @location(3) isize: f32,\n @location(4) iuv: vec2<f32>,",
"score": 10.472116533158262
}
] | typescript | camera.getMatrixInverse()
); |
import ConstrainSimulation from './constrain';
import ComputeLines from './lines';
import StepSimulation from './step';
import { LineBuffer, UniformsBuffer } from './types';
class Simulation {
private buffers?: {
data: GPUBuffer;
joints: GPUBuffer;
lines: GPUBuffer;
points: GPUBuffer[];
};
private count: number = 0;
private device: GPUDevice;
private initial?: {
joints: ArrayBuffer;
points: ArrayBuffer;
};
private pipelines?: {
constraint: ConstrainSimulation,
lines: ComputeLines,
step: StepSimulation,
};
private step: number = 0;
private readonly uniforms: UniformsBuffer;
constructor(device: GPUDevice) {
this.device = device;
this.uniforms = new UniformsBuffer(device);
}
compute(
command: GPUCommandEncoder,
delta: number,
pointer: { button: number; position: [number, number] | Float32Array; },
radius: number
) {
const { buffers, pipelines, step, uniforms } = this;
if (!buffers || !pipelines) {
return;
}
uniforms.delta = delta;
uniforms.button = pointer.button;
uniforms.pointer = pointer.position;
uniforms.radius = radius;
uniforms.update();
const pass = command.beginComputePass();
pipelines.step.compute(pass, step);
this.step = (this.step + 1) % 2;
| pipelines.constraint.compute(pass, this.step); |
pipelines.lines.compute(pass, this.step);
pass.end();
}
getBuffers() {
const { buffers, count, step } = this;
if (!buffers) {
throw new Error("Simulation is not loaded");
}
return {
count,
data: buffers.data,
lines: buffers.lines,
points: buffers.points[step],
};
}
load(
{ data, joints, numJoints, points, numPoints }: {
data: ArrayBuffer;
joints: ArrayBuffer;
numJoints: number;
points: ArrayBuffer;
numPoints: number;
}
) {
const { device } = this;
const createBuffer = (data: ArrayBuffer, usage: number) => {
const buffer = device.createBuffer({
mappedAtCreation: true,
size: data.byteLength,
usage,
});
new Uint32Array(buffer.getMappedRange()).set(new Uint32Array(data));
buffer.unmap();
return buffer;
};
if (this.buffers) {
this.buffers.data.destroy();
this.buffers.joints.destroy();
this.buffers.lines.destroy();
this.buffers.points.forEach((buffer) => buffer.destroy());
}
this.buffers = {
data: createBuffer(
data,
GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX
),
joints: createBuffer(
joints,
GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE
),
lines: LineBuffer(device, numJoints),
points: Array.from({ length: 2 }, () => createBuffer(
points,
GPUBufferUsage.COPY_DST
| GPUBufferUsage.STORAGE
| GPUBufferUsage.VERTEX
)),
};
this.count = numPoints;
this.initial = { joints, points };
this.pipelines = {
constraint: new ConstrainSimulation(
device,
this.buffers.data,
this.buffers.joints,
numJoints,
this.buffers.lines,
this.buffers.points,
numPoints
),
lines: new ComputeLines(
device,
this.buffers.joints,
numJoints,
this.buffers.lines,
this.buffers.points,
numPoints,
this.uniforms.getBuffer()
),
step: new StepSimulation(
device,
this.buffers.data,
this.buffers.points,
numPoints,
this.uniforms.getBuffer()
),
};
}
reset() {
const { buffers, device, initial } = this;
if (!buffers || !initial) {
return;
}
device.queue.writeBuffer(buffers.joints, 0, initial.joints);
buffers.points.forEach((buffer) => (
device.queue.writeBuffer(buffer, 0, initial.points)
));
}
}
export default Simulation;
| src/compute/simulation/index.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/compute/simulation/constrain.ts",
"retrieved_chunk": " })),\n };\n }\n compute(pass: GPUComputePassEncoder, step: number) {\n const { bindings, pipeline } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(1);\n }",
"score": 45.426230543260154
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " }\n compute(pass: GPUComputePassEncoder, step: number) {\n const { bindings, pipeline, workgroups } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(workgroups);\n }\n}\nexport default StepSimulation;",
"score": 43.403637051998
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " }\n var joint = joints[index];\n if (joint.enabled == 0) {\n return;\n }\n if (uniforms.button == 2) {\n if (\n sdSegment(uniforms.pointer, points[joint.a], points[joint.b]) <= uniforms.radius * 0.25\n ) {\n joints[index].enabled = 0;",
"score": 40.55238407060066
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " if (length(d) < min(uniforms.radius * 4, 24)) {\n point += d * uniforms.radius * uniforms.delta;\n }\n }\n }\n output[index] = point;\n}\n`;\nclass StepSimulation {\n private readonly bindings: {",
"score": 39.071055201806004
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " {\n binding: 0,\n resource: { buffer },\n },\n ],\n })),\n };\n this.workgroups = Math.ceil(numJoints / 256);\n }\n compute(pass: GPUComputePassEncoder, step: number) {",
"score": 37.57629168809279
}
] | typescript | pipelines.constraint.compute(pass, this.step); |
import Camera from './camera';
class Renderer {
private readonly animation: {
clock: number;
loop: (command: GPUCommandEncoder, delta: number, time: number) => void;
request: number;
};
private readonly camera: Camera;
private readonly canvas: HTMLCanvasElement;
private readonly context: GPUCanvasContext;
private readonly descriptor: GPURenderPassDescriptor;
private readonly device: GPUDevice;
private readonly format: GPUTextureFormat;
private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];
private readonly samples: number = 4;
private target: GPUTexture = undefined as unknown as GPUTexture;
constructor(camera: Camera, device: GPUDevice) {
this.camera = camera;
this.canvas = document.createElement('canvas');
const context = this.canvas.getContext('webgpu');
if (!context) {
throw new Error("Couldn't get GPUCanvasContext");
}
this.context = context;
this.format = navigator.gpu.getPreferredCanvasFormat();
this.context.configure({ alphaMode: 'opaque', device, format: this.format });
this.descriptor = {
colorAttachments: [
{
clearValue: { r: 0, g: 0, b: 0, a: 1 },
loadOp: 'clear',
storeOp: 'store',
view: undefined as unknown as GPUTextureView,
},
],
};
this.device = device;
this.objects = [];
this.animate = this.animate.bind(this);
this.animation = {
clock: performance.now() / 1000,
loop: () => {},
request: requestAnimationFrame(this.animate),
};
this.visibilitychange = this.visibilitychange.bind(this);
document.addEventListener('visibilitychange', this.visibilitychange);
}
add(object: { render: (pass: GPURenderPassEncoder) => void }) {
this.objects.push(object);
}
getCanvas() {
return this.canvas;
}
getFormat() {
return this.format;
}
getSamples() {
return this.samples;
}
setAnimationLoop(loop: (command: GPUCommandEncoder, delta: number, time: number) => void) {
this.animation.loop = loop;
}
setSize(width: number, height: number) {
const {
camera,
canvas,
descriptor: { colorAttachments: [color] },
device,
format,
samples,
target,
} = this;
const pixelRatio = window.devicePixelRatio || 1;
const size = [Math.floor(width * pixelRatio), Math.floor(height * pixelRatio)];
canvas.width = size[0];
canvas.height = size[1];
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
| camera.setAspect(width / height); |
if (target) {
target.destroy();
}
this.target = device.createTexture({
format,
sampleCount: samples,
size,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
color!.view = this.target.createView();
}
private animate() {
const { animation, device } = this;
const time = performance.now() / 1000;
const delta = Math.min(time - animation.clock, 0.1);
animation.clock = time;
animation.request = requestAnimationFrame(this.animate);
const command = device.createCommandEncoder();
animation.loop(command, delta, time);
this.render(command);
device.queue.submit([command.finish()]);
}
private render(command: GPUCommandEncoder) {
const {
context,
descriptor,
objects,
} = this;
const { colorAttachments: [color] } = descriptor;
color!.resolveTarget = context.getCurrentTexture().createView();
const pass = command.beginRenderPass(descriptor);
objects.forEach((object) => object.render(pass));
pass.end();
}
private visibilitychange() {
const { animation } = this;
cancelAnimationFrame(animation.request);
if (document.visibilityState === 'visible') {
animation.clock = performance.now() / 1000;
animation.request = requestAnimationFrame(this.animate);
}
}
}
export default Renderer;
| src/render/renderer.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/points.ts",
"retrieved_chunk": " }\n let x = 0;\n let y = 0;\n let w = canvas.width = 512;\n let h = canvas.height = 512;\n if (image.width / image.height > w / h) {\n w = image.width * canvas.height / image.height;\n x = (canvas.width - w) * 0.5;\n } else {\n h = image.height * canvas.width / image.width;",
"score": 62.57477817671917
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");\n }\n canvas.width = canvas.height = 512;\n for (let i = 0; i < 256; i++) {\n ctx.fillStyle = `hsl(${360 * Math.random()},${20 + 40 * Math.random()}%,${20 + 40 * Math.random()}%)`;\n ctx.beginPath();\n ctx.arc(canvas.width * Math.random(), canvas.height * Math.random(), 16 + Math.random() * 64, 0, Math.PI * 2);",
"score": 53.58364282662629
},
{
"filename": "src/compute/input.ts",
"retrieved_chunk": " ctx.strokeStyle = '#111';\n ctx.arc(canvas.width * 0.5, canvas.height * 0.5, 6, 0, Math.PI * 2);\n ctx.stroke();\n ctx.lineWidth = 3;\n ctx.strokeStyle = '#eee';\n ctx.stroke();\n canvas.toBlob((blob) => {\n if (blob) {\n document.body.style.cursor = `url(${URL.createObjectURL(blob)}) 10 10, default`;\n }",
"score": 46.81976843851988
},
{
"filename": "src/compute/input.ts",
"retrieved_chunk": " target.addEventListener('pointerup', this.onPointerUp.bind(this));\n {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");\n }\n canvas.width = 20;\n canvas.height = 20;\n ctx.lineWidth = 5;",
"score": 46.77185497539774
},
{
"filename": "src/render/geometry.ts",
"retrieved_chunk": "export const Plane = (device: GPUDevice, width: number = 1, height: number = 1) => {\n const buffer = device.createBuffer({\n mappedAtCreation: true,\n size: 24 * Float32Array.BYTES_PER_ELEMENT,\n usage: GPUBufferUsage.VERTEX,\n });\n new Float32Array(buffer.getMappedRange()).set([\n width * -0.5, height * 0.5, 0, 1,\n width * 0.5, height * 0.5, 1, 1,\n width * 0.5, height * -0.5, 1, 0,",
"score": 43.88982304921645
}
] | typescript | camera.setAspect(width / height); |
import './main.css';
import Camera from './render/camera';
import Input from './compute/input';
import Lines from './render/lines';
import Points from './render/points';
import Renderer from './render/renderer';
import Simulation from './compute/simulation';
import { Cloth, Ropes } from './compute/generation';
const Main = (device: GPUDevice) => {
const dom = document.getElementById('app');
if (!dom) {
throw new Error("Couldn't get app DOM node");
}
const camera = new Camera(device);
const renderer = new Renderer(camera, device);
const input = new Input(renderer.getCanvas());
const simulation = new Simulation(device);
dom.appendChild(renderer.getCanvas());
renderer.setAnimationLoop((command, delta) => (
simulation.compute(command, delta, input.getPointer(camera), camera.getZoom() * 0.02)
));
renderer.setSize(window.innerWidth, window.innerHeight);
simulation.load(Cloth());
const lines = new Lines(camera, device, renderer.getFormat(), renderer.getSamples(), simulation);
renderer.add(lines);
const points = new Points(camera, device, renderer.getFormat(), renderer.getSamples(), simulation);
renderer.add(points);
input.setHotkeys({
1: () => simulation.load(Cloth()),
2: () => simulation.load(Cloth(false, true)),
3: () => simulation.load(Ropes()),
4: () => simulation.load(Cloth(true, false)),
5: () => simulation.load(Cloth(true, true)),
escape: () => simulation.reset(),
'?': () => document.getElementById('help')?.classList.toggle('hidden'),
});
window.addEventListener('drop', (e) => {
e.preventDefault();
const [file] = e.dataTransfer?.files || [];
if (file && file.type.indexOf('image/') === 0) {
points | .setTexture(file); |
}
});
window.addEventListener('resize', () => (
renderer.setSize(window.innerWidth, window.innerHeight)
));
window.addEventListener('wheel', ({ deltaY }) => (
camera.setZoom(Math.min(Math.max(camera.getZoom() * (1 + deltaY * 0.001), 200), 400))
));
};
const GPU = async () => {
if (!navigator.gpu) {
throw new Error("Couldn't load WebGPU");
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
throw new Error("Couldn't load WebGPU adapter");
}
const device = await adapter.requestDevice();
if (!device) {
throw new Error("Couldn't load WebGPU device");
}
return device;
};
const prevent = (e: DragEvent | MouseEvent | TouchEvent) => e.preventDefault();
window.addEventListener('contextmenu', prevent);
window.addEventListener('dragenter', prevent);
window.addEventListener('dragover', prevent);
window.addEventListener('touchstart', prevent);
GPU()
.then(Main)
.catch((e) => {
document.getElementById('error')!.innerText = e.message;
document.getElementById('support')!.classList.remove('hidden');
})
.finally(() => document.getElementById('loading')!.classList.add('hidden'));
| src/main.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/points.ts",
"retrieved_chunk": " pass.setVertexBuffer(2, data);\n pass.draw(6, count, 0, 0);\n }\n setTexture(file: Blob) {\n const image = new Image();\n image.addEventListener('load', () => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");",
"score": 32.156579108377
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " y = (canvas.height - h) * 0.5;\n }\n ctx.imageSmoothingEnabled = true;\n ctx.imageSmoothingQuality = 'high';\n ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h);\n this.updateTexture(canvas);\n });\n image.src = URL.createObjectURL(file);\n }\n private generateDefaultTexture() {",
"score": 27.131763354978645
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " this.simulation = simulation;\n this.generateDefaultTexture();\n }\n render(pass: GPURenderPassEncoder) {\n const { bindings, geometry, pipeline, simulation } = this;\n const { count, data, points } = simulation.getBuffers();\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings);\n pass.setVertexBuffer(0, geometry);\n pass.setVertexBuffer(1, points);",
"score": 11.036550813573498
},
{
"filename": "src/render/lines.ts",
"retrieved_chunk": " binding: 0,\n resource: { buffer: camera.getBuffer() },\n },\n ],\n });\n this.simulation = simulation;\n }\n render(pass: GPURenderPassEncoder) {\n const { bindings, geometry, pipeline, simulation } = this;\n const { lines } = simulation.getBuffers();",
"score": 10.725605511992715
},
{
"filename": "src/compute/generation/cloth.ts",
"retrieved_chunk": " size: 1.5 + Math.random() * 0.5,\n uv: {\n x: (x + 0.5) / width,\n y: (y + 0.5) / height,\n },\n });\n if (x < width - 1) {\n joints.push({\n enabled: true,\n a: i,",
"score": 10.420346420691315
}
] | typescript | .setTexture(file); |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) isize: f32,
@location(4) iuv: vec2<f32>,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) size: f32,
@location(1) uv: vec2<f32>,
@location(2) uv2: vec2<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vertex.isize + vertex.iposition, 0, 1);
out.size = vertex.isize;
out.uv = (vertex.uv - 0.5) * 2;
out.uv2 = vertex.iuv;
return out;
}
`;
const Fragment = /* wgsl */`
struct FragmentInput {
@location(0) size: f32,
@location(1) uv: vec2<f32>,
@location(2) uv2: vec2<f32>,
}
@group(0) @binding(1) var texture: texture_2d<f32>;
@group(0) @binding(2) var textureSampler: sampler;
fn linearTosRGB(linear: vec3<f32>) -> vec3<f32> {
if (all(linear <= vec3<f32>(0.0031308))) {
return linear * 12.92;
}
return (pow(abs(linear), vec3<f32>(1.0/2.4)) * 1.055) - vec3<f32>(0.055);
}
@fragment
fn main(fragment: FragmentInput) -> @location(0) vec4<f32> {
let l = min(length(fragment.uv), 1);
var uv = fragment.uv2 + (fragment.uv / fragment.size / 33);
return vec4<f32>(linearTosRGB(
textureSample(texture, textureSampler, uv).xyz + smoothstep(0.5, 1, l) * 0.1
), smoothstep(1, 0.8, l));
}
`;
class Points {
private readonly bindings: GPUBindGroup;
private readonly device: GPUDevice;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
private readonly texture: GPUTexture;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
this.device = device;
this.geometry = Plane(device, 2, 2);
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 3,
offset: 1 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{
format,
blend: {
color: {
srcFactor: 'src-alpha',
dstFactor: 'one-minus-src-alpha',
operation: 'add',
},
alpha: {
srcFactor: 'src-alpha',
dstFactor: 'one-minus-src-alpha',
operation: 'add',
},
},
}],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.texture = device.createTexture({
dimension: '2d',
format: 'rgba8unorm-srgb',
size: [512, 512],
usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
| resource: { buffer: camera.getBuffer() },
},
{ |
binding: 1,
resource: this.texture.createView(),
},
{
binding: 2,
resource: device.createSampler({ minFilter: 'linear', magFilter: 'linear' }),
},
],
});
this.simulation = simulation;
this.generateDefaultTexture();
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { count, data, points } = simulation.getBuffers();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, points);
pass.setVertexBuffer(2, data);
pass.draw(6, count, 0, 0);
}
setTexture(file: Blob) {
const image = new Image();
image.addEventListener('load', () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
let x = 0;
let y = 0;
let w = canvas.width = 512;
let h = canvas.height = 512;
if (image.width / image.height > w / h) {
w = image.width * canvas.height / image.height;
x = (canvas.width - w) * 0.5;
} else {
h = image.height * canvas.width / image.width;
y = (canvas.height - h) * 0.5;
}
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h);
this.updateTexture(canvas);
});
image.src = URL.createObjectURL(file);
}
private generateDefaultTexture() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
canvas.width = canvas.height = 512;
for (let i = 0; i < 256; i++) {
ctx.fillStyle = `hsl(${360 * Math.random()},${20 + 40 * Math.random()}%,${20 + 40 * Math.random()}%)`;
ctx.beginPath();
ctx.arc(canvas.width * Math.random(), canvas.height * Math.random(), 16 + Math.random() * 64, 0, Math.PI * 2);
ctx.fill();
}
this.updateTexture(canvas);
}
private async updateTexture(canvas: HTMLCanvasElement) {
const { device, texture } = this;
const source = await createImageBitmap(canvas)
device.queue.copyExternalImageToTexture({ source, flipY: true }, { texture }, [512, 512]);
}
}
export default Points;
| src/render/points.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " });\n this.bindings = {\n data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: data },\n },\n {",
"score": 27.28902487113771
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " target.destroy();\n }\n this.target = device.createTexture({\n format,\n sampleCount: samples,\n size,\n usage: GPUTextureUsage.RENDER_ATTACHMENT,\n });\n color!.view = this.target.createView();\n }",
"score": 26.10395395332337
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: joints },\n },\n {\n binding: 1,\n resource: { buffer: lines },",
"score": 25.60949939839054
},
{
"filename": "src/compute/simulation/constrain.ts",
"retrieved_chunk": " ],\n }),\n points: points.map((buffer) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [\n {\n binding: 0,\n resource: { buffer },\n },\n ],",
"score": 24.927811707023
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " },\n {\n binding: 2,\n resource: { buffer: uniforms },\n },\n ],\n }),\n points: points.map((buffer) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [",
"score": 24.105329415726636
}
] | typescript | resource: { buffer: camera.getBuffer() },
},
{ |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
| htmlParser: NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
}
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })",
"score": 46.7315897353872
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 33.78531452473969
},
{
"filename": "src/notion-logger.ts",
"retrieved_chunk": " 'failedCalls' |\n 'succeededCalls'>\n constructor({ debug = false }: { debug: boolean }) {\n this.debug = debug\n this.stats = {\n totalAPICalls: 0,\n succeededCalls: 0,\n failedCalls: 0,\n }\n }",
"score": 31.772409560388372
},
{
"filename": "src/types.ts",
"retrieved_chunk": " route: string\n slug: string\n }\n}\nexport type Properties = Partial<PageObjectResponse['properties']>\nexport interface Options {\n databaseId: string\n notionAPIKey: string\n debug?: boolean\n draftMode?: boolean",
"score": 24.526018127784106
},
{
"filename": "src/notion-logger.ts",
"retrieved_chunk": "/* eslint-disable no-console */\nimport type { Stats } from './types'\nconst START = 'request start'\nconst SUCCESS = 'request success'\nconst FAILURE = 'request fail'\ntype ExtraInfo = Record<string, unknown>\nexport default class NotionLogger {\n debug: boolean\n stats: Pick<Stats,\n 'totalAPICalls' |",
"score": 21.042010269476133
}
] | typescript | htmlParser: NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
import { getMetadataKey, isDefined, isDefinedAsObject } from "~/utils";
import type {
MarkdownCodeBlockTimelineProcessingContext,
CompleteCardContext,
} from "~/types";
import { parse } from "yaml";
import {
getAbstractDateFromMetadata,
getBodyFromContextOrDocument,
getImageUrlFromContextOrDocument,
getTagsFromMetadataOrTagObject,
} from "./cardDataExtraction";
/**
* A un-changeable key used to check if a note is eligeable for render.
*/
const RENDER_GREENLIGHT_METADATA_KEY = ["aat-render-enabled"];
/**
* Provides additional context for the creation cards in the DOM.
*
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteMetadata(
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
) {
const { cachedMetadata, settings } = context;
const { frontmatter: metaData, tags } = cachedMetadata;
if (!metaData) return undefined;
if (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))
return undefined;
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
metaData,
tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;
return {
cardData: await extractCardData(context),
context,
} as const;
}
/**
* Provides additional context for the creation cards in the DOM but reads it from the body
*
* @param body - The extracted body for a single event card.
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteBody(
body: string | undefined | null,
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
): Promise<CompleteCardContext[]> {
const { settings } = context;
if (!body) return [];
const inlineEventBlockRegExp = new RegExp(
`%%${settings.noteInlineEventKey}\n(((\\s|\\d|[a-z]|-)*):(.*)\n)*%%`,
"gi"
);
const originalFrontmatter = context.cachedMetadata.frontmatter;
const matches = body.match(inlineEventBlockRegExp);
if (!matches) return [];
matches.unshift();
const output: CompleteCardContext[] = [];
for (const block of matches) {
const sanitizedBlock = block.split("\n");
sanitizedBlock.shift();
sanitizedBlock.pop();
const fakeFrontmatter = parse(sanitizedBlock.join("\n")); // this actually works lmao
// Replace frontmatter with newly built fake one. Just to re-use all the existing code.
context.cachedMetadata.frontmatter = fakeFrontmatter;
if (! | isDefinedAsObject(fakeFrontmatter)) continue; |
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
fakeFrontmatter,
context.cachedMetadata.tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;
const matchPositionInBody = body.indexOf(block);
output.push({
cardData: await extractCardData(
context,
matchPositionInBody !== -1
? body.slice(matchPositionInBody + block.length)
: undefined
),
context,
});
}
context.cachedMetadata.frontmatter = originalFrontmatter;
return output;
}
/**
* Checks if the extracted tags match at least one of the tags to find.
*
* @param timelineTags - The extracted tags from the note.
* @param tagsToFind - The tags to find.
* @returns `true` if valid.
*/
function extractedTagsAreValid(
timelineTags: string[],
tagsToFind: string[]
): boolean {
return timelineTags.some((tag) => tagsToFind.includes(tag));
}
/**
* Get the content of a card from a note. This function will parse the raw text content of a note and format it.
*
* @param context - Timeline generic context.
* @param rawFileContent - If you already have it, will avoid reading the file again.
* @returns The extracted data to create a card from a note.
*/
export async function extractCardData(
context: MarkdownCodeBlockTimelineProcessingContext,
rawFileContent?: string
) {
const { file, cachedMetadata: c, settings } = context;
const fileTitle =
c.frontmatter?.[settings.metadataKeyEventTitleOverride] ||
file.basename;
rawFileContent = rawFileContent || (await file.vault.cachedRead(file));
return {
title: fileTitle as string,
body: getBodyFromContextOrDocument(rawFileContent, context),
imageURL: getImageUrlFromContextOrDocument(rawFileContent, context),
startDate: getAbstractDateFromMetadata(
context,
settings.metadataKeyEventStartDate
),
endDate:
getAbstractDateFromMetadata(
context,
settings.metadataKeyEventEndDate
) ??
(isDefined(
getMetadataKey(c, settings.metadataKeyEventEndDate, "boolean")
)
? true
: undefined),
} as const;
}
export type FnExtractCardData = typeof extractCardData;
| src/cardData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t\tsettings: { metadataKeyEventBodyOverride },\n\t} = context;\n\tconst overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;\n\tif (!rawFileText.length || overrideBody) return overrideBody;\n\tconst rawTextArray = rawFileText.split(\"\\n\");\n\trawTextArray.shift();\n\tconst processedArray = rawTextArray.slice(rawTextArray.indexOf(\"---\") + 1);\n\tconst finalString = processedArray.join(\"\\n\").trim();\n\treturn finalString;\n}",
"score": 25.74569422325357
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t// Breakout earlier if we don't check the tags\n\tif (!settings.lookForTagsForTimeline) return output;\n\tif (isDefinedAsArray(tags))\n\t\toutput = output.concat(tags.map(({ tag }) => tag.substring(1)));\n\t// Tags in the frontmatter\n\tconst metadataInlineTags = metaData.tags;\n\tif (!isDefined(metadataInlineTags)) return output;\n\tif (isDefinedAsString(metadataInlineTags))\n\t\toutput = output.concat(\n\t\t\tmetadataInlineTags.split(\",\").map((e) => e.trim())",
"score": 19.580388479169144
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treadonly tagsToFind: string[];\n\treadonly settingsOverride: Partial<AutoTimelineSettings>;\n} {\n\tconst sourceEntries = source.split(\"\\n\");\n\tif (!source.length)\n\t\treturn { tagsToFind: [] as string[], settingsOverride: {} } as const;\n\tconst tagsToFind = sourceEntries[0]\n\t\t.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)\n\t\t.map((e) => e.trim());\n\tsourceEntries.shift();",
"score": 18.110664915630256
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): string | null {\n\tconst {\n\t\tcachedMetadata: { frontmatter: metadata },\n\t\tfile: currentFile,\n\t\tapp,\n\t\tsettings: { metadataKeyEventPictureOverride },\n\t} = context;\n\tconst {\n\t\tvault,\n\t\tmetadataCache: { getFirstLinkpathDest },",
"score": 17.530226476188783
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "import { SETTINGS_DEFAULT } from \"~/settings\";\nimport { AutoTimelineSettings } from \"./types\";\nimport { isDefined, isDefinedAsBoolean, isDefinedAsString } from \"./utils\";\n/**\n * Fetches the tags to find and timeline specific settings override.\n *\n * @param source - The markdown code block source, a.k.a. the content inside the code block.\n * @returns Partial settings to override the global ones.\n */\nexport function parseMarkdownBlockSource(source: string): {",
"score": 15.755798210430683
}
] | typescript | isDefinedAsObject(fakeFrontmatter)) continue; |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
| await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined); |
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 55.30487408518588
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tconst fileTitle =\n\t\tc.frontmatter?.[settings.metadataKeyEventTitleOverride] ||\n\t\tfile.basename;\n\trawFileContent = rawFileContent || (await file.vault.cachedRead(file));\n\treturn {\n\t\ttitle: fileTitle as string,\n\t\tbody: getBodyFromContextOrDocument(rawFileContent, context),\n\t\timageURL: getImageUrlFromContextOrDocument(rawFileContent, context),\n\t\tstartDate: getAbstractDateFromMetadata(\n\t\t\tcontext,",
"score": 49.97515397641858
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,",
"score": 34.9963853634213
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 32.120286973751895
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tcontext,\n\t} as const;\n}\n/**\n * Provides additional context for the creation cards in the DOM but reads it from the body\n *\n * @param body - The extracted body for a single event card.\n * @param context - Timeline generic context.\n * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.",
"score": 30.779065900430325
}
] | typescript | await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined); |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: NotionBlocksHtmlParser
plainTextParser | : NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
}
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })",
"score": 46.7315897353872
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 33.78531452473969
},
{
"filename": "src/notion-logger.ts",
"retrieved_chunk": " 'failedCalls' |\n 'succeededCalls'>\n constructor({ debug = false }: { debug: boolean }) {\n this.debug = debug\n this.stats = {\n totalAPICalls: 0,\n succeededCalls: 0,\n failedCalls: 0,\n }\n }",
"score": 31.772409560388372
},
{
"filename": "src/types.ts",
"retrieved_chunk": " route: string\n slug: string\n }\n}\nexport type Properties = Partial<PageObjectResponse['properties']>\nexport interface Options {\n databaseId: string\n notionAPIKey: string\n debug?: boolean\n draftMode?: boolean",
"score": 24.526018127784106
},
{
"filename": "src/notion-logger.ts",
"retrieved_chunk": "/* eslint-disable no-console */\nimport type { Stats } from './types'\nconst START = 'request start'\nconst SUCCESS = 'request success'\nconst FAILURE = 'request fail'\ntype ExtraInfo = Record<string, unknown>\nexport default class NotionLogger {\n debug: boolean\n stats: Pick<Stats,\n 'totalAPICalls' |",
"score": 21.042010269476133
}
] | typescript | : NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
import { MarkdownRenderChild, MarkdownRenderer } from "obsidian";
import { isDefined, createElementShort } from "~/utils";
import type {
MarkdownCodeBlockTimelineProcessingContext,
CardContent,
AutoTimelineSettings,
} from "~/types";
import { formatAbstractDate } from "./abstractDateFormatting";
/**
* Generates a card in the DOM based on given ccontext.
*
* @param param0 - The context built for this timeline.
* @param param0.elements - The HTMLElements exposed for this context.
* @param param0.elements.cardListRootElement - The right side of the timeline, this is where the carads are spawned.
* @param param0.file - The target note file.
* @param param0.settings - The plugin's settings.
* @param cardContent - The content of a single timeline card.
*/
export function createCardFromBuiltContext(
{
elements: { cardListRootElement },
file,
settings,
}: MarkdownCodeBlockTimelineProcessingContext,
cardContent: CardContent
): void {
const { body, title, imageURL } = cardContent;
const cardBaseDiv = createElementShort(cardListRootElement, "a", [
"internal-link",
"aat-card",
]);
cardBaseDiv.setAttribute("href", file.path);
if (imageURL) {
createElementShort(cardBaseDiv, "img", "aat-card-image").setAttribute(
"src",
imageURL
);
cardBaseDiv.addClass("aat-card-has-image");
}
const cardTextWraper = createElementShort(
cardBaseDiv,
"div",
"aat-card-text-wraper"
);
const titleWrap = createElementShort(
cardTextWraper,
"header",
"aat-card-head-wrap"
);
createElementShort(titleWrap, "h2", "aat-card-title", title);
createElementShort(
titleWrap,
"h4",
"aat-card-start-date",
getDateText(cardContent, settings).trim()
);
const markdownTextWrapper = createElementShort(
cardTextWraper,
"div",
"aat-card-body"
);
const rendered = new MarkdownRenderChild(markdownTextWrapper);
rendered.containerEl = markdownTextWrapper;
MarkdownRenderer.renderMarkdown(
formatBodyForCard(body),
markdownTextWrapper,
file.path,
rendered
);
}
/**
* Format the body string of the note data for a single card.
*
* @param body - The body string parsed earlier.
* @returns The formated string ready to be displayed.
*/
export function formatBodyForCard(body?: string | null): string {
if (!body) return "No body for this note :(";
// Remove external image links
return (
body
.replace(/!\[.*\]\(.*\)/gi, "")
// Remove tags
.replace(/#[a-zA-Z\d-_]*/gi, "")
// Remove internal images ![[Pasted image 20230418232101.png]]
.replace(/!\[\[.*\]\]/gi, "")
// Remove other timelines to avoid circular dependencies!
.replace(/```aat-vertical\n.*\n```/gi, "")
// Trim the text
.trim()
);
}
/**
* Get the text displayed in the card where the date should be.
*
* @param param0 - The context for a single card.
* @param param0.startDate - the start date of an event.
* @param param0.endDate - the end date of an event.
* @param settings - The settings of the plugin.
* @returns a formated string representation of the dates included in the card content based off the settings.
*/
export function getDateText(
{ startDate, endDate }: Pick<CardContent, "startDate" | "endDate">,
settings: AutoTimelineSettings
): string {
if (!isDefined(startDate)) return "Start date missing";
| const formatedStart = formatAbstractDate(startDate, settings); |
if (!isDefined(endDate)) return formatedStart;
return `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;
}
| src/cardMarkup.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0",
"score": 36.120037368149006
},
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": " * @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.\n * @returns the formated representation of a given date based off the plugins settings.\n */\nexport function formatAbstractDate(\n\tdate: AbstractDate | boolean,\n\t{\n\t\tdateDisplayFormat,\n\t\tdateParserGroupPriority,\n\t\tdateTokenConfiguration,\n\t\tapplyAdditonalConditionFormatting,",
"score": 35.514949231288995
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string",
"score": 33.6586083254246
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||",
"score": 29.595082255803355
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t\t\t\t(date !== true && compareAbstractDates(startDate, date) > 0)\n\t\t);\n\t\t// Over the color limit\n\t\tif (offsetIndex === -1) return;\n\t\trenderSingleRange(range, offsetIndex, rootElement);\n\t\tendDates[offsetIndex] = endDate;\n\t});\n}\n/**\n * Renders a single range element based off the offset computed previously.",
"score": 29.237995295611956
}
] | typescript | const formatedStart = formatAbstractDate(startDate, settings); |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: NotionBlocksHtmlParser
| plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
}
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })",
"score": 46.7315897353872
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 33.78531452473969
},
{
"filename": "src/notion-logger.ts",
"retrieved_chunk": " 'failedCalls' |\n 'succeededCalls'>\n constructor({ debug = false }: { debug: boolean }) {\n this.debug = debug\n this.stats = {\n totalAPICalls: 0,\n succeededCalls: 0,\n failedCalls: 0,\n }\n }",
"score": 31.772409560388372
},
{
"filename": "src/types.ts",
"retrieved_chunk": " route: string\n slug: string\n }\n}\nexport type Properties = Partial<PageObjectResponse['properties']>\nexport interface Options {\n databaseId: string\n notionAPIKey: string\n debug?: boolean\n draftMode?: boolean",
"score": 24.526018127784106
},
{
"filename": "src/notion-logger.ts",
"retrieved_chunk": "/* eslint-disable no-console */\nimport type { Stats } from './types'\nconst START = 'request start'\nconst SUCCESS = 'request success'\nconst FAILURE = 'request fail'\ntype ExtraInfo = Record<string, unknown>\nexport default class NotionLogger {\n debug: boolean\n stats: Pick<Stats,\n 'totalAPICalls' |",
"score": 21.042010269476133
}
] | typescript | plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
import fs from 'node:fs'
import { Buffer } from 'node:buffer'
import { fileTypeFromBuffer } from 'file-type'
import { nanoid } from 'nanoid'
import sharp from 'sharp'
import type { Content, PageContent, PluginExecOptions } from '../types'
interface ImageCacheEntry {
filename?: string
location?: string
url?: string
}
interface ImageCache { [key: string]: Array<ImageCacheEntry> }
const IMAGE_FILE_MATCH_REGEX = /(.*)X-Amz-Algorithm/g
const IMAGE_CACHE_FILENAME = 'ncms-image-cache.json'
const GENERIC_MATCH = /\b(https?:\/\/[\w_#&?.\/-]*?\.(?:png|jpe?g|svg|ico))(?=[`'")\]])/ig
const IMAGE_SOURCE_MATCH = /<img[^>]*src=['|"](https?:\/\/[^'|"]+)(?:['|"])/ig
function multiStringMatch(stringA: unknown, stringB: unknown): Boolean {
if (typeof stringA !== 'string' || typeof stringB !== 'string' || !stringA || !stringB)
return false
const matchA = stringA.match(IMAGE_FILE_MATCH_REGEX)
const matchB = stringB.match(IMAGE_FILE_MATCH_REGEX)
return Boolean(matchA && matchB && (matchA[0] === matchB[0]))
}
export default function ({
globalExtension = 'webp',
compression = 80,
imageCacheDirectory = './public',
customMatchers = [],
}: {
globalExtension?: 'webp' | 'png' | 'jpeg'
compression?: number
imageCacheDirectory?: string
customMatchers?: RegExp[]
} = {}) {
let imageCache: ImageCache
try {
// Pull existing imageCache
if (fs.existsSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`)) {
imageCache = JSON.parse(
fs.readFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, 'utf-8')) as ImageCache
}
else {
imageCache = {}
}
}
catch (e) {
console.warn(e, 'ncms-plugin-images: error attempting to read image cache.')
imageCache = {}
}
async function writeOutImage(imageUrl: string, existingImageFile: ImageCacheEntry): Promise<string> {
let filename = ''
if (existingImageFile)
return existingImageFile.filename as string
const response = await fetch(imageUrl)
const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
const fileType = await fileTypeFromBuffer(buffer)
if (fileType?.ext) {
const id = nanoid(6)
filename = `${id}.remote.${globalExtension}`
const outputFilePath = `${imageCacheDirectory}/remote/${filename}`
const imageBuffer = sharp(buffer)
const webPBuffer = await imageBuffer[globalExtension]({
quality: compression,
nearLossless: true,
effort: 6,
}).toBuffer()
const writeStream = fs.createWriteStream(outputFilePath)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
writeStream.on('error', err => console.warn(`ncms-plugin-images: failed to write image file: ${err}`))
writeStream.write(webPBuffer)
}
return filename
}
function detectExisting(path: string, imageUrl: string): ImageCacheEntry {
const entries = imageCache[path]
return entries.filter((entry) => {
return multiStringMatch(entry.url, imageUrl) || multiStringMatch(entry.location, imageUrl)
})[0]
}
async function processImage(
path: string,
imageUrl: string,
updator: { update: Content | string },
debug?: boolean): Promise<void> {
if (imageUrl && path) {
let filename = ''
try {
filename = await writeOutImage(imageUrl, detectExisting(path, imageUrl))
}
catch (e) {
if (debug)
console.warn('ncms-plugin-images: File type could not be reliably determined! The binary data may be malformed! No file saved!')
return
}
if (filename) {
imageCache[path].push({
filename,
location: `/remote/${filename}`,
url: imageUrl,
})
// if we don't do this, the replaceall cant find the proper url below
if (typeof updator.update !== 'string') {
if (updator.update?.html.includes('amazonaws'))
updator.update.html = updator.update.html.replaceAll('&', '&')
updator.update.html = updator.update.html.replace(imageUrl, `/remote/${filename}`)
}
else {
// This replaces the coverImage
updator.update = updator.update.replace(imageUrl, `/remote/${filename}`)
}
if (debug)
console.log('ncms-plugin-images: rewriting', path, 'at', filename)
}
}
}
return {
name: 'ncms-plugin-images',
hook: 'during-tree',
core: true,
exec | : async (context: PageContent, options: PluginExecOptions) => { |
const copyOfContext = structuredClone(context)
if (!copyOfContext.path)
return
const matchables = [
GENERIC_MATCH,
IMAGE_SOURCE_MATCH,
...customMatchers,
]
if (!imageCache[copyOfContext.path])
imageCache[copyOfContext.path] = [] as ImageCacheEntry[]
const contents = {
update: copyOfContext.content as Content,
}
const coverImage = {
update: copyOfContext.coverImage as string,
}
// Must run all async in series so that we don't end up with duplicates
for (const match of matchables) {
if (!copyOfContext.path)
return
const path = copyOfContext.path
const matched = (contents.update && Array.from(contents.update.html.matchAll(match), m => m[1])) || []
const matchedCoverImages = (coverImage.update && [coverImage.update]) || []
for (const imageUrl of matched)
await processImage(path, imageUrl, contents, options.debug)
for (const imageUrl of matchedCoverImages)
await processImage(path, imageUrl, coverImage, options.debug)
}
copyOfContext.content = contents.update
copyOfContext.coverImage = coverImage.update
try {
if (!fs.existsSync(`${imageCacheDirectory}/remote`))
fs.mkdirSync(`${imageCacheDirectory}/remote`)
fs.writeFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, JSON.stringify(imageCache))
if (options.debug)
fs.writeFileSync('debug/images.json', JSON.stringify(imageCache))
}
catch (e) {
if (options.debug)
console.warn(e, 'ncms-plugin-images: error writing to image cache.')
}
return copyOfContext
},
}
}
| src/plugins/images.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/head.ts",
"retrieved_chunk": "import type { PageContent } from '../types'\nexport default function () {\n return {\n name: 'ncms-plugin-head',\n hook: 'during-tree',\n core: true,\n exec: (context: PageContent) => {\n const copyOfContext = structuredClone(context) as PageContentWithMeta\n copyOfContext.meta = {\n title: '',",
"score": 50.5743827208465
},
{
"filename": "src/plugins/linker.ts",
"retrieved_chunk": " exec: (context: PageContent) => {\n const copyOfContext = structuredClone(context)\n if (copyOfContext._notion?.id && copyOfContext.path)\n links.set(copyOfContext._notion?.id, copyOfContext.path)\n return copyOfContext\n },\n },\n {\n name: 'ncms-plugin-linker',\n hook: 'post-tree',",
"score": 42.062925150642094
},
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": " return {\n parser,\n name: 'ncms-plugin-blocks-render',\n core: true,\n hook: 'parse',\n exec: (context: PluginPassthrough): string => {\n const copyOfContext = _.cloneDeep(context) as Blocks\n return parser.blocksToHtml(copyOfContext)\n },\n } satisfies UnsafePlugin",
"score": 39.79201312203331
},
{
"filename": "src/types.ts",
"retrieved_chunk": " name: string\n hook: 'import' | 'pre-tree' | 'pre-parse' | 'post-parse' | 'during-tree' | 'post-tree' | '*'\n exec: (context: PluginPassthrough, instanceOptions?: PluginExecOptions) => PluginPassthrough\n}\nexport interface UnsafePlugin {\n parser: NotionBlocksParser\n name: string\n core: boolean\n hook: 'parse' | 'import' | 'pre-tree' | 'pre-parse' | 'post-parse' | 'during-tree' | 'post-tree' | '*'\n exec: (context: PluginPassthrough, instanceOptions?: PluginExecOptions) => PluginPassthrough",
"score": 39.52911369301406
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " databaseId: '610627a9-28b1-4477-b660-c00c5364435b',\n notionAPIKey,\n draftMode: true,\n // Standin Plugin - use default renderer plugin behind the scenes\n plugins: [() => ({\n name: 'ncms-placeholder-plugin',\n hook: 'post-parse',\n exec: (block: Block) => block,\n })],\n })",
"score": 28.52473549986932
}
] | typescript | : async (context: PageContent, options: PluginExecOptions) => { |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: | NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
}
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })",
"score": 46.7315897353872
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 33.78531452473969
},
{
"filename": "src/notion-logger.ts",
"retrieved_chunk": " 'failedCalls' |\n 'succeededCalls'>\n constructor({ debug = false }: { debug: boolean }) {\n this.debug = debug\n this.stats = {\n totalAPICalls: 0,\n succeededCalls: 0,\n failedCalls: 0,\n }\n }",
"score": 31.772409560388372
},
{
"filename": "src/types.ts",
"retrieved_chunk": " route: string\n slug: string\n }\n}\nexport type Properties = Partial<PageObjectResponse['properties']>\nexport interface Options {\n databaseId: string\n notionAPIKey: string\n debug?: boolean\n draftMode?: boolean",
"score": 24.526018127784106
},
{
"filename": "src/notion-logger.ts",
"retrieved_chunk": "/* eslint-disable no-console */\nimport type { Stats } from './types'\nconst START = 'request start'\nconst SUCCESS = 'request success'\nconst FAILURE = 'request fail'\ntype ExtraInfo = Record<string, unknown>\nexport default class NotionLogger {\n debug: boolean\n stats: Pick<Stats,\n 'totalAPICalls' |",
"score": 21.042010269476133
}
] | typescript | NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab( | new TimelineSettingTab(this.app, this)); |
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\t? compareAbstractDates(startDate, date) <= 0\n\t\t\t\t: false\n\t);\n\tif (firstLastUnderIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members\"\n\t\t);\n\tconst lastUnderIndex = collection.findIndex(\n\t\t({ cardData: { startDate } }, index) => {\n\t\t\treturn (",
"score": 34.16007905891004
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\t\t};\n\t\t\t\t\t\tvalue.value = this.plugin.settings;\n\t\t\t\t\t\tawait this.plugin.saveSettings();\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t\tmethods: {},\n\t\t});\n\t\tthis.vueApp.use(i18n).mount(this.containerEl);\n\t}",
"score": 31.869477142503566
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\tcomponents: { VApp },\n\t\t\ttemplate: \"<VApp :value='value' @update:value='save' />\",\n\t\t\tsetup: () => {\n\t\t\t\tconst value = ref(this.plugin.settings);\n\t\t\t\treturn {\n\t\t\t\t\tvalue,\n\t\t\t\t\tsave: async (payload: Partial<AutoTimelineSettings>) => {\n\t\t\t\t\t\tthis.plugin.settings = {\n\t\t\t\t\t\t\t...this.plugin.settings,\n\t\t\t\t\t\t\t...payload,",
"score": 29.373907039626296
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tconstructor(app: ObsidianApp, plugin: AprilsAutomaticTimelinesPlugin) {\n\t\tsuper(app, plugin);\n\t\tthis.plugin = plugin;\n\t\tthis.vueApp = null;\n\t}\n\tdisplay(): void {\n\t\tthis.containerEl.empty();\n\t\t// TODO Read locale off obsidian.\n\t\tconst i18n = createVueI18nConfig();\n\t\tthis.vueApp = createApp({",
"score": 29.326619452491432
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tarr: T,\n\tpredicate: (arg: T[number]) => boolean\n): number {\n\tconst length = arr ? arr.length : 0;\n\tif (!length) return -1;\n\tlet index = length - 1;\n\twhile (index--) if (predicate(arr[index])) return index;\n\treturn -1;\n}\n/**",
"score": 27.64131019369504
}
] | typescript | new TimelineSettingTab(this.app, this)); |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser | = new NotionBlocksHtmlParser(this.mdParser, this.debug)
} |
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 48.45648474902242
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " async _parsePageContent(pageContent: BlockObjectResponse[]): Promise<Content> {\n const results = await this._runPlugins(pageContent as Blocks, 'pre-parse')\n const markdown: string = this.coreRenderer.parser.blocksToMarkdown(pageContent as Blocks)\n const plaintext: string = this.coreRenderer.parser.markdownToPlainText(markdown)\n const parsedBlocks = await this._runPlugins(results as Blocks, 'parse')\n const html = await this._runPlugins(parsedBlocks, 'post-parse') as string\n return {\n plaintext,\n markdown,\n html,",
"score": 40.168127595831436
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " this.logger = new NotionLogger({ debug: this.debug })\n this.notionClient = new Client({\n auth: notionAPIKey,\n logLevel: LogLevel.DEBUG,\n logger: this.logger.log.bind(this.logger),\n })\n this.autoUpdate = autoUpdate\n this.refreshTimeout\n = (refreshTimeout && _.isString(refreshTimeout))\n ? (humanInterval(refreshTimeout) || refreshTimeout)",
"score": 37.72660036758026
},
{
"filename": "src/notion-blocks-md-parser.ts",
"retrieved_chunk": " }\n return embedded.concat(EOL_MD)\n }\n parseRichTexts(richTexts: RichText[]): string {\n return richTexts.reduce((parsedContent, richText) => {\n switch (richText.type) {\n case 'text':\n parsedContent += this.parseText(richText)\n break\n case 'mention':",
"score": 36.72017241905379
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " : (refreshTimeout || 0)\n this.draftMode = draftMode || false\n this.localCacheDirectory = localCacheDirectory\n this.defaultCacheFilename = `ncms-cache-${this.cmsId}.json`\n this.localCacheUrl = path.resolve(__dirname, this.localCacheDirectory + this.defaultCacheFilename)\n this.limiter = limiter\n this.limiter.schedule.bind(limiter)\n this.coreRenderer = renderer({ blockRenderers: {}, debug })\n this.coreRenderer.name = 'core-renderer'\n this.plugins = this._dedupePlugins([...plugins, this.coreRenderer])",
"score": 36.36788519077641
}
] | typescript | = new NotionBlocksHtmlParser(this.mdParser, this.debug)
} |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = | compareAbstractDates(a, b); |
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0",
"score": 27.390574055044482
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\trelatedCardData: {\n\t\t\t\t\t...relatedCardData,\n\t\t\t\t\tcardData: {\n\t\t\t\t\t\t...relatedCardData.cardData,\n\t\t\t\t\t\tendDate,\n\t\t\t\t\t\tstartDate,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\ttargetPosition,\n\t\t\t\tcardRelativeTopPosition,",
"score": 23.01266242488445
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tindex,\n\t\t\t} as const);\n\t\t\treturn accumulator;\n\t\t},\n\t\t[] as {\n\t\t\treadonly relatedCardData: CompleteCardContext & {\n\t\t\t\tcardData: CompleteCardContext[\"cardData\"] & {\n\t\t\t\t\tstartDate: AbstractDate;\n\t\t\t\t\tendDate: AbstractDate | true;\n\t\t\t\t};",
"score": 20.742916821386956
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||",
"score": 19.235176669295395
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": " */\nexport function getDateText(\n\t{ startDate, endDate }: Pick<CardContent, \"startDate\" | \"endDate\">,\n\tsettings: AutoTimelineSettings\n): string {\n\tif (!isDefined(startDate)) return \"Start date missing\";\n\tconst formatedStart = formatAbstractDate(startDate, settings);\n\tif (!isDefined(endDate)) return formatedStart;\n\treturn `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;\n}",
"score": 17.684497364792723
}
] | typescript | compareAbstractDates(a, b); |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
| this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
} |
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 64.64771885347398
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " async _parsePageContent(pageContent: BlockObjectResponse[]): Promise<Content> {\n const results = await this._runPlugins(pageContent as Blocks, 'pre-parse')\n const markdown: string = this.coreRenderer.parser.blocksToMarkdown(pageContent as Blocks)\n const plaintext: string = this.coreRenderer.parser.markdownToPlainText(markdown)\n const parsedBlocks = await this._runPlugins(results as Blocks, 'parse')\n const html = await this._runPlugins(parsedBlocks, 'post-parse') as string\n return {\n plaintext,\n markdown,\n html,",
"score": 49.5693768909073
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " this.logger = new NotionLogger({ debug: this.debug })\n this.notionClient = new Client({\n auth: notionAPIKey,\n logLevel: LogLevel.DEBUG,\n logger: this.logger.log.bind(this.logger),\n })\n this.autoUpdate = autoUpdate\n this.refreshTimeout\n = (refreshTimeout && _.isString(refreshTimeout))\n ? (humanInterval(refreshTimeout) || refreshTimeout)",
"score": 49.246529526842664
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " : (refreshTimeout || 0)\n this.draftMode = draftMode || false\n this.localCacheDirectory = localCacheDirectory\n this.defaultCacheFilename = `ncms-cache-${this.cmsId}.json`\n this.localCacheUrl = path.resolve(__dirname, this.localCacheDirectory + this.defaultCacheFilename)\n this.limiter = limiter\n this.limiter.schedule.bind(limiter)\n this.coreRenderer = renderer({ blockRenderers: {}, debug })\n this.coreRenderer.name = 'core-renderer'\n this.plugins = this._dedupePlugins([...plugins, this.coreRenderer])",
"score": 47.6372392524038
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " this.pull = this.fetch.bind(this)\n this.rootAlias = rootAlias\n this.withinRefreshTimeout = false\n this.quietMode = quiet\n }\n get data() {\n if (_.isEmpty(this.cms.siteData))\n return\n return this.cms.siteData\n }",
"score": 43.98520409053441
}
] | typescript | this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
} |
import { MarkdownRenderChild, MarkdownRenderer } from "obsidian";
import { isDefined, createElementShort } from "~/utils";
import type {
MarkdownCodeBlockTimelineProcessingContext,
CardContent,
AutoTimelineSettings,
} from "~/types";
import { formatAbstractDate } from "./abstractDateFormatting";
/**
* Generates a card in the DOM based on given ccontext.
*
* @param param0 - The context built for this timeline.
* @param param0.elements - The HTMLElements exposed for this context.
* @param param0.elements.cardListRootElement - The right side of the timeline, this is where the carads are spawned.
* @param param0.file - The target note file.
* @param param0.settings - The plugin's settings.
* @param cardContent - The content of a single timeline card.
*/
export function createCardFromBuiltContext(
{
elements: { cardListRootElement },
file,
settings,
}: MarkdownCodeBlockTimelineProcessingContext,
cardContent: CardContent
): void {
const { body, title, imageURL } = cardContent;
const cardBaseDiv = createElementShort(cardListRootElement, "a", [
"internal-link",
"aat-card",
]);
cardBaseDiv.setAttribute("href", file.path);
if (imageURL) {
createElementShort(cardBaseDiv, "img", "aat-card-image").setAttribute(
"src",
imageURL
);
cardBaseDiv.addClass("aat-card-has-image");
}
const cardTextWraper = createElementShort(
cardBaseDiv,
"div",
"aat-card-text-wraper"
);
const titleWrap = createElementShort(
cardTextWraper,
"header",
"aat-card-head-wrap"
);
createElementShort(titleWrap, "h2", "aat-card-title", title);
createElementShort(
titleWrap,
"h4",
"aat-card-start-date",
getDateText(cardContent, settings).trim()
);
const markdownTextWrapper = createElementShort(
cardTextWraper,
"div",
"aat-card-body"
);
const rendered = new MarkdownRenderChild(markdownTextWrapper);
rendered.containerEl = markdownTextWrapper;
MarkdownRenderer.renderMarkdown(
formatBodyForCard(body),
markdownTextWrapper,
file.path,
rendered
);
}
/**
* Format the body string of the note data for a single card.
*
* @param body - The body string parsed earlier.
* @returns The formated string ready to be displayed.
*/
export function formatBodyForCard(body?: string | null): string {
if (!body) return "No body for this note :(";
// Remove external image links
return (
body
.replace(/!\[.*\]\(.*\)/gi, "")
// Remove tags
.replace(/#[a-zA-Z\d-_]*/gi, "")
// Remove internal images ![[Pasted image 20230418232101.png]]
.replace(/!\[\[.*\]\]/gi, "")
// Remove other timelines to avoid circular dependencies!
.replace(/```aat-vertical\n.*\n```/gi, "")
// Trim the text
.trim()
);
}
/**
* Get the text displayed in the card where the date should be.
*
* @param param0 - The context for a single card.
* @param param0.startDate - the start date of an event.
* @param param0.endDate - the end date of an event.
* @param settings - The settings of the plugin.
* @returns a formated string representation of the dates included in the card content based off the settings.
*/
export function getDateText(
{ startDate, endDate }: Pick<CardContent, "startDate" | "endDate">,
settings: AutoTimelineSettings
): string {
| if (!isDefined(startDate)) return "Start date missing"; |
const formatedStart = formatAbstractDate(startDate, settings);
if (!isDefined(endDate)) return formatedStart;
return `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;
}
| src/cardMarkup.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string",
"score": 40.71304260118392
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0",
"score": 36.12003736814901
},
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": " * @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.\n * @returns the formated representation of a given date based off the plugins settings.\n */\nexport function formatAbstractDate(\n\tdate: AbstractDate | boolean,\n\t{\n\t\tdateDisplayFormat,\n\t\tdateParserGroupPriority,\n\t\tdateTokenConfiguration,\n\t\tapplyAdditonalConditionFormatting,",
"score": 33.26976571297878
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t}\n\treturn [0, 1, 1];\n}\ntype Boundary = { date: AbstractDate; top: number };\n/**\n * Find the position of the last card having a lower start date and the first card with a higher start date relative to the endDate of the evaluated range.\n *\n * @param date - The target endDate to position on the timeline.\n * @param collection - The collection of cards part of the same timeline.\n * @param rootElement - The root HTMLElement of the cardList.",
"score": 31.71351641971067
},
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": "\tAdditionalDateFormatting,\n} from \"~/types\";\n/**\n * Handy function to format an abstract date based on the current settings.\n *\n * @param date - Target date to format.\n * @param param1 - The settings of the plugin.\n * @param param1.dateDisplayFormat - The target format to displat the date in.\n * @param param1.dateParserGroupPriority - The token priority list for the date format.\n * @param param1.dateTokenConfiguration - The configuration for the given date format.",
"score": 31.38208086112283
}
] | typescript | if (!isDefined(startDate)) return "Start date missing"; |
import dotenv from 'dotenv'
import { suite } from 'uvu'
import * as assert from 'uvu/assert'
import nock from 'nock'
import NotionCMS from '../index'
import type { CMS, PluginPassthrough } from '../types'
dotenv.config()
export const TestNotionCMSCache = suite('TestNotionCMSCache')
const cachingDatabaseId = '1234' // this does not exist in notion
const baseUrl = 'https://api.notion.com/v1'
const cachingTestCMS: NotionCMS = new NotionCMS({
databaseId: cachingDatabaseId,
notionAPIKey: process.env.NOTION as string,
draftMode: true,
})
cachingTestCMS.purgeCache()
const topLevelPageId = '456'
const topLevelPageId2 = '789'
TestNotionCMSCache('Unchanged since last edit time uses cache', async () => {
nock(baseUrl)
.post(`/databases/${cachingDatabaseId}/query`)
.query(true)
.reply(200, {
object: 'list',
results: [
{
object: 'page',
id: topLevelPageId,
created_time: '2023-04-09T06:03:00.000Z',
last_edited_time: '2023-04-09T06:03:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
properties: {
name: {
id: 'title',
type: 'title',
title: [
{
type: 'text',
text: {
content: 'Page 1',
link: null,
},
annotations: {},
plain_text: 'Page 1',
href: null,
},
],
},
Author: {
id: 'SQeZ',
type: 'people',
people: [
{
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
name: 'Jacob',
avatar_url: null,
type: 'person',
person: {
email: '[email protected]',
},
},
],
},
Tags: {
id: 'NNmP',
type: 'multi_select',
multi_select: [
{
id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18',
name: 'programming',
color: 'default',
},
],
},
},
cover: null,
icon: null,
archived: false,
url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d',
},
{
object: 'page',
id: topLevelPageId2,
created_time: '2023-04-09T06:03:00.000Z',
last_edited_time: '2023-04-09T06:03:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
properties: {
name: {
id: 'title',
type: 'title',
title: [
{
type: 'text',
text: {
content: 'Page 2',
link: null,
},
annotations: {},
plain_text: 'Page 2',
href: null,
},
],
},
Author: {
id: 'SQeZ',
type: 'people',
people: [
{
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
name: 'Jacob',
avatar_url: null,
type: 'person',
person: {
email: '[email protected]',
},
},
],
},
Tags: {
id: 'NNmP',
type: 'multi_select',
multi_select: [
{
id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18',
name: 'programming',
color: 'default',
},
],
},
},
cover: null,
icon: null,
archived: false,
url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d',
},
],
next_cursor: null,
has_more: false,
type: 'page',
page: {},
})
nock(baseUrl)
.get(`/blocks/${topLevelPageId}/children`)
.query(true)
.reply(200, {
object: 'list',
results: [
{
object: 'block',
id: '1c92a5ea-dfeb-4c8f-b662-cde078bb02ad',
parent: {
type: 'page_id',
page_id: topLevelPageId,
},
created_time: '2023-04-22T04:34:00.000Z',
last_edited_time: '2023-04-22T04:34:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
has_children: false,
archived: false,
type: 'heading_1',
heading_1: {
rich_text: [
{
type: 'text',
text: {
content: 'Block 1: Has not changed.',
link: null,
},
annotations: {},
plain_text: 'Block 1: Has not changed.',
href: null,
},
],
is_toggleable: false,
color: 'default',
},
},
],
})
nock(baseUrl)
.get(`/blocks/${topLevelPageId2}/children`)
.query(true)
.reply(200, {
object: 'list',
results: [
{
object: 'block',
id: '1c92a5ea-dfeb-4c8f-b662-cde078bb02ad',
parent: {
type: 'page_id',
page_id: topLevelPageId2,
},
created_time: '2023-04-22T04:34:00.000Z',
last_edited_time: '2023-04-22T04:34:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
has_children: false,
archived: false,
type: 'heading_1',
heading_1: {
rich_text: [
{
type: 'text',
text: {
content: 'Block 2: Has not changed.',
link: null,
},
annotations: {},
plain_text: 'Block 2: Has not changed.',
href: null,
},
],
is_toggleable: false,
color: 'default',
},
},
],
})
// Build the cache
const cms: CMS = await cachingTestCMS.pull()
assert.ok(cms.siteData['/page-1'].content?.plaintext === 'Block 1: Has not changed.')
assert.ok(cms.siteData['/page-2'].content?.plaintext === 'Block 2: Has not changed.')
// Change some data in only page 2
nock(baseUrl)
.post(`/databases/${cachingDatabaseId}/query`)
.query(true)
.reply(200, {
object: 'list',
results: [
{
object: 'page',
id: topLevelPageId,
created_time: '2023-04-09T06:03:00.000Z',
last_edited_time: '2023-04-09T06:03:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
properties: {
name: {
id: 'title',
type: 'title',
title: [
{
type: 'text',
text: {
content: 'Page 1',
link: null,
},
annotations: {},
plain_text: 'Page 1',
href: null,
},
],
},
Author: {
id: 'SQeZ',
type: 'people',
people: [
{
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
name: 'Jacob',
avatar_url: null,
type: 'person',
person: {
email: '[email protected]',
},
},
],
},
Tags: {
id: 'NNmP',
type: 'multi_select',
multi_select: [
{
id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18',
name: 'programming',
color: 'default',
},
],
},
},
cover: null,
icon: null,
archived: false,
url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d',
},
{
object: 'page',
id: topLevelPageId2,
created_time: '2023-04-09T06:03:00.000Z',
last_edited_time: '2023-04-09T06:16:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
properties: {
name: {
id: 'title',
type: 'title',
title: [
{
type: 'text',
text: {
content: 'Page 2',
link: null,
},
annotations: {},
plain_text: 'Page 2',
href: null,
},
],
},
Author: {
id: 'SQeZ',
type: 'people',
people: [
{
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
name: 'Jacob',
avatar_url: null,
type: 'person',
person: {
email: '[email protected]',
},
},
],
},
Tags: {
id: 'NNmP',
type: 'multi_select',
multi_select: [
{
id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18',
name: 'programming',
color: 'default',
},
],
},
},
cover: null,
icon: null,
archived: false,
url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d',
},
],
next_cursor: null,
has_more: false,
type: 'page',
page: {},
})
nock(baseUrl)
.get(`/blocks/${topLevelPageId2}/children`)
.query(true)
.reply(200, {
object: 'list',
results: [
{
object: 'block',
id: '1c92a5ea-dfeb-4c8f-b662-cde078bb02ad',
parent: {
type: 'page_id',
page_id: topLevelPageId2,
},
created_time: '2023-04-22T04:34:00.000Z',
last_edited_time: '2023-04-22T04:34:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
has_children: false,
archived: false,
type: 'heading_1',
heading_1: {
rich_text: [
{
type: 'text',
text: {
content: 'Block 2: Has changed.',
link: null,
},
annotations: {},
plain_text: 'Block 2: Has changed.',
href: null,
},
],
is_toggleable: false,
color: 'default',
},
},
],
})
const cms2: CMS = await cachingTestCMS.pull()
assert.ok(cms2.siteData['/page-1'].content?.plaintext === 'Block 1: Has not changed.')
assert.ok(cms2.siteData['/page-2'].content?.plaintext === 'Block 2: Has changed.')
})
TestNotionCMSCache('Plugins run even when using cached state.', async () => {
const databaseId = '610627a9-28b1-4477-b660-c00c5364435b'
let counter = 0
const testCMS: NotionCMS = new NotionCMS({
databaseId,
notionAPIKey: process.env.NOTION as string,
draftMode: true,
refreshTimeout: '1 minute',
plugins: [
{
name: 'counter-plugin',
hook: '*', // this will run every hook
| exec: (ctx: PluginPassthrough) => { |
counter++
return ctx
},
},
],
})
console.log('caching test: purging cache')
testCMS.purgeCache()
await testCMS.pull()
assert.equal(counter, 22)
})
| src/tests/notion-cms-caching.spec.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/tests/limiter.spec.ts",
"retrieved_chunk": "const limiter = new Bottleneck({\n maxConcurrent: 1,\n minTime: 333,\n})\nconst testCMS = new NotionCMS({\n databaseId,\n notionAPIKey: process.env.NOTION,\n draftMode: true,\n limiter,\n})",
"score": 52.32757698135984
},
{
"filename": "src/tests/notion-cms.spec.ts",
"retrieved_chunk": " databaseId,\n notionAPIKey: process.env.NOTION,\n draftMode: true,\n plugins: [() => 'test plugin'],\n }\n const newOptions = {\n databaseId,\n notionAPIKey: process.env.NOTION,\n draftMode: false,\n }",
"score": 51.37599580274766
},
{
"filename": "src/tests/notion-cms.spec.ts",
"retrieved_chunk": " }\n})\nTestNotionCMS('Options have changed', () => {\n const options = {\n databaseId,\n notionAPIKey: process.env.NOTION,\n draftMode: true,\n plugins: [() => 'test plugin'],\n }\n const otherOptions = {",
"score": 42.59704107246539
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " PluginsCustomCMS = new NotionCMS({\n // Kitchen sink DB in community/tests\n databaseId,\n notionAPIKey,\n // Should work with other plugin too\n plugins: [() => ({\n name: 'ncms-placeholder-plugin',\n hook: 'post-parse',\n exec: (block: Block) => block,\n }),",
"score": 37.97205244321488
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " hook: Plugin['hook'] | 'parse'): Promise<PluginPassthrough> {\n if (!this.plugins?.length)\n return context\n if (this._checkDuplicateParsePlugins(this.plugins))\n throw new Error('Only one parse-capable plugin must be used. Use the default NotionCMS render plugin.')\n let val = context\n for (const plugin of this.plugins.flat()) {\n if (plugin.hook === hook || plugin.hook === '*') {\n // eslint-disable-next-line @typescript-eslint/await-thenable\n val = await plugin.exec(val, {",
"score": 37.2467064813161
}
] | typescript | exec: (ctx: PluginPassthrough) => { |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const | baseData = await getDataFromNoteMetadata(context, tagsToFind); |
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": "import type { App } from \"obsidian\";\nimport type {\n\tAutoTimelineSettings,\n\tMarkdownCodeBlockTimelineProcessingContext,\n} from \"~/types\";\n/**\n * A preliminary helper to fetch all the needed context to handle the timeline creation.\n *\n * @param app - The app context provided by obsidian.\n * @param element - The root element of this timeline.",
"score": 16.121672954120886
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 13.55105752641202
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 13.327734148969103
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,",
"score": 12.129409272499736
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 12.04223231704816
}
] | typescript | baseData = await getDataFromNoteMetadata(context, tagsToFind); |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
| prioArray.forEach((token, index) => { |
const configuration = dateTokenConfiguration.find(
({ name }) => name === token
);
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),",
"score": 24.89461654637352
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];\nconst acceptedSettingsOverride = [\n\t\"dateDisplayFormat\",\n\t\"applyAdditonalConditionFormatting\",\n] as const;\n/**\n * Checks if a given string is part of the settings keys that can be overriden.\n *\n * @param value - A given settings key.\n * @returns the typeguard boolean `true` if the key is indeed overridable.",
"score": 17.397290522715092
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 13.512396312624674
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\tindex < this.settings.dateTokenConfiguration.length;\n\t\t\tindex++\n\t\t) {\n\t\t\tthis.settings.dateTokenConfiguration[index].formatting =\n\t\t\t\tthis.settings.dateTokenConfiguration[index].formatting || [];\n\t\t}\n\t\tthis.addSettingTab(new TimelineSettingTab(this.app, this));\n\t}\n\t/**\n\t * Saves the settings in obsidian.",
"score": 10.886847563663624
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tarr: T,\n\tpredicate: (arg: T[number]) => boolean\n): number {\n\tconst length = arr ? arr.length : 0;\n\tif (!length) return -1;\n\tlet index = length - 1;\n\twhile (index--) if (predicate(arr[index])) return index;\n\treturn -1;\n}\n/**",
"score": 10.673775168294478
}
] | typescript | prioArray.forEach((token, index) => { |
import fs from 'node:fs'
import { Buffer } from 'node:buffer'
import { fileTypeFromBuffer } from 'file-type'
import { nanoid } from 'nanoid'
import sharp from 'sharp'
import type { Content, PageContent, PluginExecOptions } from '../types'
interface ImageCacheEntry {
filename?: string
location?: string
url?: string
}
interface ImageCache { [key: string]: Array<ImageCacheEntry> }
const IMAGE_FILE_MATCH_REGEX = /(.*)X-Amz-Algorithm/g
const IMAGE_CACHE_FILENAME = 'ncms-image-cache.json'
const GENERIC_MATCH = /\b(https?:\/\/[\w_#&?.\/-]*?\.(?:png|jpe?g|svg|ico))(?=[`'")\]])/ig
const IMAGE_SOURCE_MATCH = /<img[^>]*src=['|"](https?:\/\/[^'|"]+)(?:['|"])/ig
function multiStringMatch(stringA: unknown, stringB: unknown): Boolean {
if (typeof stringA !== 'string' || typeof stringB !== 'string' || !stringA || !stringB)
return false
const matchA = stringA.match(IMAGE_FILE_MATCH_REGEX)
const matchB = stringB.match(IMAGE_FILE_MATCH_REGEX)
return Boolean(matchA && matchB && (matchA[0] === matchB[0]))
}
export default function ({
globalExtension = 'webp',
compression = 80,
imageCacheDirectory = './public',
customMatchers = [],
}: {
globalExtension?: 'webp' | 'png' | 'jpeg'
compression?: number
imageCacheDirectory?: string
customMatchers?: RegExp[]
} = {}) {
let imageCache: ImageCache
try {
// Pull existing imageCache
if (fs.existsSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`)) {
imageCache = JSON.parse(
fs.readFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, 'utf-8')) as ImageCache
}
else {
imageCache = {}
}
}
catch (e) {
console.warn(e, 'ncms-plugin-images: error attempting to read image cache.')
imageCache = {}
}
async function writeOutImage(imageUrl: string, existingImageFile: ImageCacheEntry): Promise<string> {
let filename = ''
if (existingImageFile)
return existingImageFile.filename as string
const response = await fetch(imageUrl)
const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
const fileType = await fileTypeFromBuffer(buffer)
if (fileType?.ext) {
const id = nanoid(6)
filename = `${id}.remote.${globalExtension}`
const outputFilePath = `${imageCacheDirectory}/remote/${filename}`
const imageBuffer = sharp(buffer)
const webPBuffer = await imageBuffer[globalExtension]({
quality: compression,
nearLossless: true,
effort: 6,
}).toBuffer()
const writeStream = fs.createWriteStream(outputFilePath)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
writeStream.on('error', err => console.warn(`ncms-plugin-images: failed to write image file: ${err}`))
writeStream.write(webPBuffer)
}
return filename
}
function detectExisting(path: string, imageUrl: string): ImageCacheEntry {
const entries = imageCache[path]
return entries.filter((entry) => {
return multiStringMatch(entry.url, imageUrl) || multiStringMatch(entry.location, imageUrl)
})[0]
}
async function processImage(
path: string,
imageUrl: string,
| updator: { update: Content | string },
debug?: boolean): Promise<void> { |
if (imageUrl && path) {
let filename = ''
try {
filename = await writeOutImage(imageUrl, detectExisting(path, imageUrl))
}
catch (e) {
if (debug)
console.warn('ncms-plugin-images: File type could not be reliably determined! The binary data may be malformed! No file saved!')
return
}
if (filename) {
imageCache[path].push({
filename,
location: `/remote/${filename}`,
url: imageUrl,
})
// if we don't do this, the replaceall cant find the proper url below
if (typeof updator.update !== 'string') {
if (updator.update?.html.includes('amazonaws'))
updator.update.html = updator.update.html.replaceAll('&', '&')
updator.update.html = updator.update.html.replace(imageUrl, `/remote/${filename}`)
}
else {
// This replaces the coverImage
updator.update = updator.update.replace(imageUrl, `/remote/${filename}`)
}
if (debug)
console.log('ncms-plugin-images: rewriting', path, 'at', filename)
}
}
}
return {
name: 'ncms-plugin-images',
hook: 'during-tree',
core: true,
exec: async (context: PageContent, options: PluginExecOptions) => {
const copyOfContext = structuredClone(context)
if (!copyOfContext.path)
return
const matchables = [
GENERIC_MATCH,
IMAGE_SOURCE_MATCH,
...customMatchers,
]
if (!imageCache[copyOfContext.path])
imageCache[copyOfContext.path] = [] as ImageCacheEntry[]
const contents = {
update: copyOfContext.content as Content,
}
const coverImage = {
update: copyOfContext.coverImage as string,
}
// Must run all async in series so that we don't end up with duplicates
for (const match of matchables) {
if (!copyOfContext.path)
return
const path = copyOfContext.path
const matched = (contents.update && Array.from(contents.update.html.matchAll(match), m => m[1])) || []
const matchedCoverImages = (coverImage.update && [coverImage.update]) || []
for (const imageUrl of matched)
await processImage(path, imageUrl, contents, options.debug)
for (const imageUrl of matchedCoverImages)
await processImage(path, imageUrl, coverImage, options.debug)
}
copyOfContext.content = contents.update
copyOfContext.coverImage = coverImage.update
try {
if (!fs.existsSync(`${imageCacheDirectory}/remote`))
fs.mkdirSync(`${imageCacheDirectory}/remote`)
fs.writeFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, JSON.stringify(imageCache))
if (options.debug)
fs.writeFileSync('debug/images.json', JSON.stringify(imageCache))
}
catch (e) {
if (options.debug)
console.warn(e, 'ncms-plugin-images: error writing to image cache.')
}
return copyOfContext
},
}
}
| src/plugins/images.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " }\n _extractUnsteadyProps(properties: PageObjectResponse['properties']): PageObjectResponse['properties'] {\n return _(properties)\n .entries()\n .reject(([key]) => _.includes(STEADY_PROPS, key))\n .fromPairs().value()\n }\n _getPageUpdate(entry: PageObjectResponse): Page {\n const tags = [] as Array<string>\n if (isFullPage(entry)) {",
"score": 41.619445872712035
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " const name = this._getBlockName(entry)\n const authorProp = entry.properties?.Author as PageObjectUser\n const authors = authorProp.people.map(authorId => authorId.name as string)\n const coverImage = this._getCoverImage(entry)\n const extractedTags = this._extractTags(entry)\n extractedTags.forEach(tag => tags.push(tag))\n const otherProps = this._extractUnsteadyProps(entry.properties)\n return {\n name,\n otherProps,",
"score": 36.55244121807215
},
{
"filename": "src/utilities.ts",
"retrieved_chunk": "export function writeFile(path: string, contents: string): void {\n fs.mkdirSync(dirname(path), { recursive: true })\n fs.writeFileSync(path, contents)\n}\nexport function slugify(name: string): string {\n return _.kebabCase(name)\n}\nexport function routify(name: string): string {\n const slug = slugify(name)\n return slug.padStart(slug.length + 1, '/')",
"score": 31.88347501645667
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " .entries()\n .filter(([key]) => key.startsWith('/'))\n .map(e => e[1]).value() as Page[]\n }\n rejectSubPages(pathOrPage: string | Page): Page {\n if (typeof pathOrPage === 'string')\n pathOrPage = this.queryByPath(pathOrPage)\n return _(pathOrPage)\n .entries()\n .reject(([key]) => key.startsWith('/'))",
"score": 28.45848208401958
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " slug: slugify(name),\n authors,\n tags,\n coverImage,\n _notion: {\n id: entry.id,\n last_edited_time: entry.last_edited_time,\n },\n }\n }",
"score": 26.680011855688136
}
] | typescript | updator: { update: Content | string },
debug?: boolean): Promise<void> { |
import { SETTINGS_DEFAULT } from "~/settings";
import { AutoTimelineSettings } from "./types";
import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils";
/**
* Fetches the tags to find and timeline specific settings override.
*
* @param source - The markdown code block source, a.k.a. the content inside the code block.
* @returns Partial settings to override the global ones.
*/
export function parseMarkdownBlockSource(source: string): {
readonly tagsToFind: string[];
readonly settingsOverride: Partial<AutoTimelineSettings>;
} {
const sourceEntries = source.split("\n");
if (!source.length)
return { tagsToFind: [] as string[], settingsOverride: {} } as const;
const tagsToFind = sourceEntries[0]
.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)
.map((e) => e.trim());
sourceEntries.shift();
return {
tagsToFind,
settingsOverride: sourceEntries.reduce((accumulator, element) => {
return {
...accumulator,
...parseSingleLine(element),
};
}, {} as Partial<AutoTimelineSettings>),
} as const;
}
type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];
const acceptedSettingsOverride = [
"dateDisplayFormat",
"applyAdditonalConditionFormatting",
] as const;
/**
* Checks if a given string is part of the settings keys that can be overriden.
*
* @param value - A given settings key.
* @returns the typeguard boolean `true` if the key is indeed overridable.
*/
function isOverridableSettingsKey(
value: string
): value is OverridableSettingKey {
// @ts-expect-error
return acceptedSettingsOverride.includes(value);
}
/**
* Will apply the needed formatting to a setting value based of it's key.
*
* @param key - The settings key.
* @param value - The value associated to this value.
* @returns Undefined if unvalid or the actual expected value.
*/
function formatValueFromKey(
key: string,
value: string
): AutoTimelineSettings[OverridableSettingKey] | undefined {
if (!isOverridableSettingsKey(key)) return undefined;
| if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value; |
if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) {
const validBooleanStrings = ["true", "false"];
if (!validBooleanStrings.includes(value.toLocaleLowerCase()))
throw new Error(`${value} is supposed to be a boolean`);
return value.toLocaleLowerCase() === "true" ? true : false;
}
return undefined;
}
/**
* Parse a single line of the timeline markdown block content.
*
* @param line - The line to parse.
* @returns A potencialy partial settings object.
*/
function parseSingleLine(line: string): Partial<AutoTimelineSettings> {
const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i;
const matches = line.match(reg);
if (
!matches ||
!matches.groups ||
!isDefinedAsString(matches.groups.key) ||
!isDefined(matches.groups.value)
)
return {};
const key = matches.groups.key.trim();
const value = formatValueFromKey(key, matches.groups.value.trim());
if (!isDefined(value)) return {};
return { [key]: value };
}
| src/markdownBlockData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param cachedMetadata - cachedMetadata - Obsidians cachedMetadata object.\n * @param key - the sought after key in the obsidian metadata object.\n * @param type - The expected type of the key value.\n * @returns The metadata value assigned to the given key or null if unvalidated or missing.\n */\nexport function getMetadataKey<T extends \"string\" | \"number\" | \"boolean\">(\n\tcachedMetadata: MarkdownCodeBlockTimelineProcessingContext[\"cachedMetadata\"],\n\tkey: string,\n\ttype: T\n):",
"score": 54.763299812405634
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "}\n/**\n * Typeguard to check if a value is an object of unknowed key values.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an object, `false` if not.\n */\nexport function isDefinedAsObject(\n\tvalue: unknown\n): value is { [key: string]: unknown } {",
"score": 49.138720900461216
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\t| (T extends \"string\" ? string : T extends \"number\" ? number : boolean)\n\t| undefined {\n\t// Bail if no formatter object or if the key is missing\n\tif (!cachedMetadata.frontmatter) return undefined;\n\treturn typeof cachedMetadata.frontmatter[key] === type\n\t\t? cachedMetadata.frontmatter[key]\n\t\t: undefined;\n}\n/**\n * Typeguard to check if a value is indeed defined.",
"score": 46.84794695053824
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string",
"score": 37.542853475679976
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 32.61558077025223
}
] | typescript | if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value; |
import fs from 'node:fs'
import { Buffer } from 'node:buffer'
import { fileTypeFromBuffer } from 'file-type'
import { nanoid } from 'nanoid'
import sharp from 'sharp'
import type { Content, PageContent, PluginExecOptions } from '../types'
interface ImageCacheEntry {
filename?: string
location?: string
url?: string
}
interface ImageCache { [key: string]: Array<ImageCacheEntry> }
const IMAGE_FILE_MATCH_REGEX = /(.*)X-Amz-Algorithm/g
const IMAGE_CACHE_FILENAME = 'ncms-image-cache.json'
const GENERIC_MATCH = /\b(https?:\/\/[\w_#&?.\/-]*?\.(?:png|jpe?g|svg|ico))(?=[`'")\]])/ig
const IMAGE_SOURCE_MATCH = /<img[^>]*src=['|"](https?:\/\/[^'|"]+)(?:['|"])/ig
function multiStringMatch(stringA: unknown, stringB: unknown): Boolean {
if (typeof stringA !== 'string' || typeof stringB !== 'string' || !stringA || !stringB)
return false
const matchA = stringA.match(IMAGE_FILE_MATCH_REGEX)
const matchB = stringB.match(IMAGE_FILE_MATCH_REGEX)
return Boolean(matchA && matchB && (matchA[0] === matchB[0]))
}
export default function ({
globalExtension = 'webp',
compression = 80,
imageCacheDirectory = './public',
customMatchers = [],
}: {
globalExtension?: 'webp' | 'png' | 'jpeg'
compression?: number
imageCacheDirectory?: string
customMatchers?: RegExp[]
} = {}) {
let imageCache: ImageCache
try {
// Pull existing imageCache
if (fs.existsSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`)) {
imageCache = JSON.parse(
fs.readFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, 'utf-8')) as ImageCache
}
else {
imageCache = {}
}
}
catch (e) {
console.warn(e, 'ncms-plugin-images: error attempting to read image cache.')
imageCache = {}
}
async function writeOutImage(imageUrl: string, existingImageFile: ImageCacheEntry): Promise<string> {
let filename = ''
if (existingImageFile)
return existingImageFile.filename as string
const response = await fetch(imageUrl)
const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
const fileType = await fileTypeFromBuffer(buffer)
if (fileType?.ext) {
const id = nanoid(6)
filename = `${id}.remote.${globalExtension}`
const outputFilePath = `${imageCacheDirectory}/remote/${filename}`
const imageBuffer = sharp(buffer)
const webPBuffer = await imageBuffer[globalExtension]({
quality: compression,
nearLossless: true,
effort: 6,
}).toBuffer()
const writeStream = fs.createWriteStream(outputFilePath)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
writeStream.on('error', err => console.warn(`ncms-plugin-images: failed to write image file: ${err}`))
writeStream.write(webPBuffer)
}
return filename
}
function detectExisting(path: string, imageUrl: string): ImageCacheEntry {
const entries = imageCache[path]
return entries.filter((entry) => {
return multiStringMatch(entry.url, imageUrl) || multiStringMatch(entry.location, imageUrl)
})[0]
}
async function processImage(
path: string,
imageUrl: string,
updator: { update: Content | string },
debug?: boolean): Promise<void> {
if (imageUrl && path) {
let filename = ''
try {
filename = await writeOutImage(imageUrl, detectExisting(path, imageUrl))
}
catch (e) {
if (debug)
console.warn('ncms-plugin-images: File type could not be reliably determined! The binary data may be malformed! No file saved!')
return
}
if (filename) {
imageCache[path].push({
filename,
location: `/remote/${filename}`,
url: imageUrl,
})
// if we don't do this, the replaceall cant find the proper url below
if (typeof updator.update !== 'string') {
if (updator.update?.html.includes('amazonaws'))
updator.update.html = updator.update.html.replaceAll('&', '&')
updator.update.html = updator.update.html.replace(imageUrl, `/remote/${filename}`)
}
else {
// This replaces the coverImage
updator.update = updator.update.replace(imageUrl, `/remote/${filename}`)
}
if (debug)
console.log('ncms-plugin-images: rewriting', path, 'at', filename)
}
}
}
return {
name: 'ncms-plugin-images',
hook: 'during-tree',
core: true,
exec: async ( | context: PageContent, options: PluginExecOptions) => { |
const copyOfContext = structuredClone(context)
if (!copyOfContext.path)
return
const matchables = [
GENERIC_MATCH,
IMAGE_SOURCE_MATCH,
...customMatchers,
]
if (!imageCache[copyOfContext.path])
imageCache[copyOfContext.path] = [] as ImageCacheEntry[]
const contents = {
update: copyOfContext.content as Content,
}
const coverImage = {
update: copyOfContext.coverImage as string,
}
// Must run all async in series so that we don't end up with duplicates
for (const match of matchables) {
if (!copyOfContext.path)
return
const path = copyOfContext.path
const matched = (contents.update && Array.from(contents.update.html.matchAll(match), m => m[1])) || []
const matchedCoverImages = (coverImage.update && [coverImage.update]) || []
for (const imageUrl of matched)
await processImage(path, imageUrl, contents, options.debug)
for (const imageUrl of matchedCoverImages)
await processImage(path, imageUrl, coverImage, options.debug)
}
copyOfContext.content = contents.update
copyOfContext.coverImage = coverImage.update
try {
if (!fs.existsSync(`${imageCacheDirectory}/remote`))
fs.mkdirSync(`${imageCacheDirectory}/remote`)
fs.writeFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, JSON.stringify(imageCache))
if (options.debug)
fs.writeFileSync('debug/images.json', JSON.stringify(imageCache))
}
catch (e) {
if (options.debug)
console.warn(e, 'ncms-plugin-images: error writing to image cache.')
}
return copyOfContext
},
}
}
| src/plugins/images.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/head.ts",
"retrieved_chunk": "import type { PageContent } from '../types'\nexport default function () {\n return {\n name: 'ncms-plugin-head',\n hook: 'during-tree',\n core: true,\n exec: (context: PageContent) => {\n const copyOfContext = structuredClone(context) as PageContentWithMeta\n copyOfContext.meta = {\n title: '',",
"score": 50.5743827208465
},
{
"filename": "src/plugins/linker.ts",
"retrieved_chunk": " exec: (context: PageContent) => {\n const copyOfContext = structuredClone(context)\n if (copyOfContext._notion?.id && copyOfContext.path)\n links.set(copyOfContext._notion?.id, copyOfContext.path)\n return copyOfContext\n },\n },\n {\n name: 'ncms-plugin-linker',\n hook: 'post-tree',",
"score": 42.062925150642094
},
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": " return {\n parser,\n name: 'ncms-plugin-blocks-render',\n core: true,\n hook: 'parse',\n exec: (context: PluginPassthrough): string => {\n const copyOfContext = _.cloneDeep(context) as Blocks\n return parser.blocksToHtml(copyOfContext)\n },\n } satisfies UnsafePlugin",
"score": 39.79201312203331
},
{
"filename": "src/types.ts",
"retrieved_chunk": " name: string\n hook: 'import' | 'pre-tree' | 'pre-parse' | 'post-parse' | 'during-tree' | 'post-tree' | '*'\n exec: (context: PluginPassthrough, instanceOptions?: PluginExecOptions) => PluginPassthrough\n}\nexport interface UnsafePlugin {\n parser: NotionBlocksParser\n name: string\n core: boolean\n hook: 'parse' | 'import' | 'pre-tree' | 'pre-parse' | 'post-parse' | 'during-tree' | 'post-tree' | '*'\n exec: (context: PluginPassthrough, instanceOptions?: PluginExecOptions) => PluginPassthrough",
"score": 39.52911369301406
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " databaseId: '610627a9-28b1-4477-b660-c00c5364435b',\n notionAPIKey,\n draftMode: true,\n // Standin Plugin - use default renderer plugin behind the scenes\n plugins: [() => ({\n name: 'ncms-placeholder-plugin',\n hook: 'post-parse',\n exec: (block: Block) => block,\n })],\n })",
"score": 28.52473549986932
}
] | typescript | context: PageContent, options: PluginExecOptions) => { |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
prioArray. | forEach((token, index) => { |
const configuration = dateTokenConfiguration.find(
({ name }) => name === token
);
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),",
"score": 20.7455137886446
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];\nconst acceptedSettingsOverride = [\n\t\"dateDisplayFormat\",\n\t\"applyAdditonalConditionFormatting\",\n] as const;\n/**\n * Checks if a given string is part of the settings keys that can be overriden.\n *\n * @param value - A given settings key.\n * @returns the typeguard boolean `true` if the key is indeed overridable.",
"score": 13.686097455319459
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 13.512396312624674
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\tindex < this.settings.dateTokenConfiguration.length;\n\t\t\tindex++\n\t\t) {\n\t\t\tthis.settings.dateTokenConfiguration[index].formatting =\n\t\t\t\tthis.settings.dateTokenConfiguration[index].formatting || [];\n\t\t}\n\t\tthis.addSettingTab(new TimelineSettingTab(this.app, this));\n\t}\n\t/**\n\t * Saves the settings in obsidian.",
"score": 10.886847563663624
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tarr: T,\n\tpredicate: (arg: T[number]) => boolean\n): number {\n\tconst length = arr ? arr.length : 0;\n\tif (!length) return -1;\n\tlet index = length - 1;\n\twhile (index--) if (predicate(arr[index])) return index;\n\treturn -1;\n}\n/**",
"score": 10.673775168294478
}
] | typescript | forEach((token, index) => { |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
}
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
| return this.mdParser.parse(blocks, depth)
} |
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " async _parsePageContent(pageContent: BlockObjectResponse[]): Promise<Content> {\n const results = await this._runPlugins(pageContent as Blocks, 'pre-parse')\n const markdown: string = this.coreRenderer.parser.blocksToMarkdown(pageContent as Blocks)\n const plaintext: string = this.coreRenderer.parser.markdownToPlainText(markdown)\n const parsedBlocks = await this._runPlugins(results as Blocks, 'parse')\n const html = await this._runPlugins(parsedBlocks, 'post-parse') as string\n return {\n plaintext,\n markdown,\n html,",
"score": 70.63697390404025
},
{
"filename": "src/notion-blocks-md-parser.ts",
"retrieved_chunk": "import { uuidToId } from 'notion-utils'\nconst EOL_MD = '\\n'\nexport default class NotionBlocksMarkdownParser {\n parse(blocks: Blocks, depth = 0): string {\n return blocks\n .reduce((markdown, childBlock) => {\n let childBlockString = ''\n // @ts-expect-error children\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (childBlock.has_children && childBlock[childBlock.type].children) {",
"score": 61.2520257658572
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " }\n marked.use({ silent: true })\n // This is a workaround so that hljs doesn't complain about mermaid not being a registered lang.\n hljs.registerAliases('mermaid', { languageName: 'plaintext' })\n }\n marked(md: string): string {\n return marked(md, this.markedOptions)\n }\n parse(blocks: Blocks) {\n let markdown = this.markdownParser.parse(blocks)",
"score": 61.13394591938439
},
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": " return {\n parser,\n name: 'ncms-plugin-blocks-render',\n core: true,\n hook: 'parse',\n exec: (context: PluginPassthrough): string => {\n const copyOfContext = _.cloneDeep(context) as Blocks\n return parser.blocksToHtml(copyOfContext)\n },\n } satisfies UnsafePlugin",
"score": 46.59140493918769
},
{
"filename": "src/notion-blocks-md-parser.ts",
"retrieved_chunk": " childBlockString = ' '\n .repeat(depth)\n .concat(\n childBlockString,\n // @ts-expect-error children\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument\n this.parse(childBlock[childBlock.type].children, depth + 2),\n )\n }\n if (childBlock.type === 'unsupported') {",
"score": 44.124951774000316
}
] | typescript | return this.mdParser.parse(blocks, depth)
} |
import { PluginSettingTab } from "obsidian";
import { createApp, ref } from "vue";
import createVueI18nConfig from "~/i18n.config";
import VApp from "~/views/App.vue";
import type { App as ObsidianApp } from "obsidian";
import type AprilsAutomaticTimelinesPlugin from "~/main";
import type { AutoTimelineSettings, DateTokenConfiguration } from "./types";
import type { App as VueApp } from "vue";
import { createNumberDateTokenConfiguration } from "./utils";
/**
* Default key value relation for obsidian settings object
*/
export const SETTINGS_DEFAULT = {
metadataKeyEventStartDate: "aat-event-start-date",
metadataKeyEventEndDate: "aat-event-end-date",
metadataKeyEventTitleOverride: "aat-event-title",
metadataKeyEventBodyOverride: "aat-event-body",
metadataKeyEventPictureOverride: "aat-event-picture",
metadataKeyEventTimelineTag: "timelines",
noteInlineEventKey: "aat-inline-event",
markdownBlockTagsToFindSeparator: ",",
dateParserRegex: "(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)",
dateParserGroupPriority: "year,month,day",
dateDisplayFormat: "{day}/{month}/{year}",
lookForTagsForTimeline: false,
lookForInlineEventsInNotes: true,
applyAdditonalConditionFormatting: true,
dateTokenConfiguration: [
createNumberDateTokenConfiguration({ name: "year", minLeght: 4 }),
createNumberDateTokenConfiguration({ name: "month" }),
createNumberDateTokenConfiguration({ name: "day" }),
] as DateTokenConfiguration[],
};
export const __VUE_PROD_DEVTOOLS__ = true;
/**
* Class designed to display the inputs that allow the end user to change the default keys that are looked for when processing metadata in a single note.
*/
export class TimelineSettingTab extends PluginSettingTab {
plugin: AprilsAutomaticTimelinesPlugin;
vueApp: VueApp<Element> | null;
constructor(app: ObsidianApp, plugin: AprilsAutomaticTimelinesPlugin) {
super(app, plugin);
this.plugin = plugin;
this.vueApp = null;
}
display(): void {
this.containerEl.empty();
// TODO Read locale off obsidian.
const i18n = createVueI18nConfig();
this.vueApp = createApp({
components: { VApp },
template: "<VApp :value='value' @update:value='save' />",
setup: () => {
const value = ref(this.plugin.settings);
return {
value,
| save: async (payload: Partial<AutoTimelineSettings>) => { |
this.plugin.settings = {
...this.plugin.settings,
...payload,
};
value.value = this.plugin.settings;
await this.plugin.saveSettings();
},
};
},
methods: {},
});
this.vueApp.use(i18n).mount(this.containerEl);
}
hide() {
if (!this.vueApp) return;
this.vueApp.unmount();
this.vueApp = null;
}
}
| src/settings.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": " * @param key - The settings key.\n * @param value - The value associated to this value.\n * @returns Undefined if unvalid or the actual expected value.\n */\nfunction formatValueFromKey(\n\tkey: string,\n\tvalue: string\n): AutoTimelineSettings[OverridableSettingKey] | undefined {\n\tif (!isOverridableSettingsKey(key)) return undefined;\n\tif (isDefinedAsString(SETTINGS_DEFAULT[key])) return value;",
"score": 25.06323934056199
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\t\t!isDefinedAsString(matches.groups.key) ||\n\t\t!isDefined(matches.groups.value)\n\t)\n\t\treturn {};\n\tconst key = matches.groups.key.trim();\n\tconst value = formatValueFromKey(key, matches.groups.value.trim());\n\tif (!isDefined(value)) return {};\n\treturn { [key]: value };\n}",
"score": 19.648101777254023
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\treturn 0;\n}\n/**\n * Typeguard to check if a value is an array of unknowed sub type.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an array, `false` if not.\n */\nexport function isDefinedAsArray(value: unknown): value is unknown[] {\n\treturn isDefined(value) && value instanceof Array;",
"score": 18.567564742762606
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " *\n * @param value - Date token configuration.\n * @returns typeguard.\n */\nexport function dateTokenConfigurationIsTypeString(\n\tvalue: DateTokenConfiguration\n): value is DateTokenConfiguration<DateTokenType.string> {\n\treturn value.type === DateTokenType.string;\n}\n/**",
"score": 18.452848755471877
},
{
"filename": "src/main.ts",
"retrieved_chunk": "export default class AprilsAutomaticTimelinesPlugin extends Plugin {\n\tsettings: AutoTimelineSettings;\n\t/**\n\t * The default onload method of a obsidian plugin\n\t * See the official documentation for more details\n\t */\n\tasync onload() {\n\t\tawait this.loadSettings();\n\t\tthis.registerMarkdownCodeBlockProcessor(\n\t\t\t\"aat-vertical\",",
"score": 18.264430936522228
}
] | typescript | save: async (payload: Partial<AutoTimelineSettings>) => { |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if ( | isDefined(baseData)) events.push(baseData); |
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 17.962100027926365
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 13.722830515471829
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 12.516287987759627
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,",
"score": 12.446167566333818
},
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": "import type { App } from \"obsidian\";\nimport type {\n\tAutoTimelineSettings,\n\tMarkdownCodeBlockTimelineProcessingContext,\n} from \"~/types\";\n/**\n * A preliminary helper to fetch all the needed context to handle the timeline creation.\n *\n * @param app - The app context provided by obsidian.\n * @param element - The root element of this timeline.",
"score": 12.227006793859797
}
] | typescript | isDefined(baseData)) events.push(baseData); |
import { SETTINGS_DEFAULT } from "~/settings";
import { FnGetRangeData } from "./rangeData";
import { FnExtractCardData, getDataFromNoteMetadata } from "~/cardData";
import type { App, CachedMetadata, TFile } from "obsidian";
import type { Merge } from "ts-essentials";
/**
* @author https://stackoverflow.com/a/69756175
*/
export type PickByType<T, Value> = {
[P in keyof T as T[P] extends Value | undefined ? P : never]: T[P];
};
export type AutoTimelineSettings = typeof SETTINGS_DEFAULT;
/**
* The main bundle of data needed to build a timeline.
*/
export interface MarkdownCodeBlockTimelineProcessingContext {
/**
* Obsidian application context.
*/
app: App;
/**
* The plugins settings
*/
settings: AutoTimelineSettings;
/**
* The formatted metadata of a single note.
*/
cachedMetadata: CachedMetadata;
/**
* The file data of a single note.
*/
file: TFile;
/**
* The filepath of a single timeline.
*/
timelineFile: string;
/**
* Shorthand access to HTMLElements for the range timelines and the card list.
*/
elements: {
timelineRootElement: HTMLElement;
cardListRootElement: HTMLElement;
};
}
/**
* The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.
*/
export type CompleteCardContext = Exclude<
Awaited<ReturnType<typeof getDataFromNoteMetadata>>,
undefined
>;
/**
* The context extracted from a single note to create a single card in the timeline.
*/
| export type CardContent = Awaited<ReturnType<FnExtractCardData>>; |
/**
* The needed data to compute a range in a single timeline.
*/
export type Range = ReturnType<FnGetRangeData>[number];
/**
* An abstract representation of a fantasy date.
* Given the fickle nature of story telling and how people will literally almost never stick to standard date formats
* We'll organise the dates in segments, let's take for example our human callendar
* The date will commonly be segmented in 3 parts year, month and day the abstract representation will equate to
* `[year, month, day]`
* Now if someone wants to make a more complex date system like `[cycle, moon, phase, day]` we can treat them the same when sorting and performing computing tasks on those dates.
* The only major limitation to this system is that all the dates must respect the same system.
*/
export type AbstractDate = number[];
/**
* Before formatting an abstract date, the end user can configure it's output display
* This DateToken type helps to determine what's the nature of a given token
* E.g. should it be displayed as a number or as a string ?
*/
export enum DateTokenType {
number = "NUMBER",
string = "STRING",
}
export const availableDateTokenTypeArray = Object.values(DateTokenType);
export enum Condition {
Greater = "GREATER",
Less = "LESS",
Equal = "EQUAL",
NotEqual = "NOTEQUAL",
GreaterOrEqual = "GREATEROREQUAL",
LessOrEqual = "LESSOREQUAL",
}
export const availableConditionArray = Object.values(Condition);
export type Evaluation<T extends number = number> = {
condition: Condition;
value: T;
};
export type AdditionalDateFormatting<T extends number = number> = {
evaluations: Evaluation<T>[];
/**
* Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.
*/
conditionsAreExclusive: boolean;
/**
* Use `{value}` to include the pre-formated output of the numerical value held.
*/
format: string;
};
/**
* The data used to compute the output of an abstract date based on it's type
*/
type CommonValues<T extends DateTokenType> = {
name: string;
type: T;
formatting: AdditionalDateFormatting[];
};
export type DateTokenConfiguration<T extends DateTokenType = DateTokenType> =
T extends DateTokenType.number
? NumberSpecific
: T extends DateTokenType.string
? StringSpecific
: StringSpecific | NumberSpecific;
/**
* Number typed date token.
*/
type NumberSpecific = Merge<
CommonValues<DateTokenType.number>,
{
/**
* The minimum ammount of digits when displaying the date
*/
minLeght: number;
displayWhenZero: boolean;
hideSign: boolean;
}
>;
/**
* String typed date token.
*/
type StringSpecific = Merge<
CommonValues<DateTokenType.string>,
{
/**
* The dictionary reference for the token
*/
dictionary: string[];
}
>;
| src/types.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tcontext,\n\t} as const;\n}\n/**\n * Provides additional context for the creation cards in the DOM but reads it from the body\n *\n * @param body - The extracted body for a single event card.\n * @param context - Timeline generic context.\n * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.",
"score": 44.287688889407804
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 38.52196931038375
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": " *\n * @param param0 - The context built for this timeline.\n * @param param0.elements - The HTMLElements exposed for this context.\n * @param param0.elements.cardListRootElement - The right side of the timeline, this is where the carads are spawned.\n * @param param0.file - The target note file.\n * @param param0.settings - The plugin's settings.\n * @param cardContent - The content of a single timeline card.\n */\nexport function createCardFromBuiltContext(\n\t{",
"score": 35.07265741583444
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t(source, element, context) => {\n\t\t\t\tthis.run(source, element, context);\n\t\t\t}\n\t\t);\n\t}\n\tonunload() {}\n\t/**\n\t * Main runtime function to process a single timeline.\n\t *\n\t * @param source - The content found in the markdown block.",
"score": 34.80449022050774
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": " *\n * @param param0 - A single range.\n * @param param0.index - The index of the card.\n * @param param0.targetPosition - The target position of a given range. This determines where the rage should end.\n * @param param0.cardRelativeTopPosition - The ammount of pixel from the top of the timeline relative to a given card.\n * @param param0.relatedCardData - The associated card data.\n * @param param0.relatedCardData.context - The associated runtime context for this card.\n * @param param0.relatedCardData.context.elements - The HTMLElements exposed for this context.\n * @param param0.relatedCardData.context.elements.cardListRootElement - The right side of the timeline, this is where the carads are spawned.\n * @param param0.relatedCardData.context.elements.timelineRootElement - The base layer for the timeline.",
"score": 31.943161783068497
}
] | typescript | export type CardContent = Awaited<ReturnType<FnExtractCardData>>; |
import PROP_PREFIX from './prefix';
// part and slotted not currently supported by quarks
const PSEUDO_ELEMENTS = [
// '::part()',
// '::slotted()',
'::after',
'::backdrop',
'::before',
'::cue',
'::cue-region',
'::first-letter',
'::first-line',
'::file-selector-button',
'::grammar-error',
'::marker',
'::placeholder',
'::selection',
'::spelling-error',
'::target-text',
'::-moz-placeholder',
'::-moz-progress-bar',
'::-moz-range-progress',
'::-moz-range-thumb',
'::-moz-range-track',
'::-moz-selection',
'::-ms-backdrop',
'::-ms-browse',
'::-ms-check',
'::-ms-clear',
'::-ms-expand',
'::-ms-fill',
'::-ms-fill-lower',
'::-ms-fill-upper',
'::-ms-input-placeholder',
'::-ms-reveal',
'::-ms-thumb',
'::-ms-ticks-after',
'::-ms-ticks-before',
'::-ms-tooltip',
'::-ms-track',
'::-ms-value',
'::-webkit-backdrop',
'::-webkit-input-placeholder',
'::-webkit-progress-bar',
'::-webkit-progress-inner-value',
'::-webkit-progress-value',
'::-webkit-slider-runnable-track',
'::-webkit-slider-thumb',
];
| export const prefixedPseudoElements = PSEUDO_ELEMENTS.map(pseudoEle => pseudoEle.replace('::', PROP_PREFIX)); |
export default PSEUDO_ELEMENTS;
| src/constants/pseudoElements.ts | quarks-css-quarks-2822055 | [
{
"filename": "src/utils/propChecks.ts",
"retrieved_chunk": "export const isPseudo = (value: unknown): value is Record<string, unknown> => typeof value === 'object';\nexport const isPseudoElement = (propName: string) => prefixedPseudoElements.includes(propName);",
"score": 12.432543464299354
},
{
"filename": "src/utils/flattenObject.ts",
"retrieved_chunk": " : never\n : never;\nconst flattenObject = <T extends object>(obj: T, parentKey?: string): FlattenObjectReturn<T> => {\n const result = Object.entries(obj).reduce<FlattenObjectReturn<T>>((prevValue, [key, value]) => {\n const newKey = parentKey ? (`${parentKey}-${String(key)}` as const) : key;\n if (typeof value === 'object' && !Array.isArray(value) && value !== null) {\n return { ...prevValue, ...flattenObject(value, String(newKey)) };\n }\n return { ...prevValue, [newKey]: value };\n }, {} as FlattenObjectReturn<T>);",
"score": 8.379465319434193
},
{
"filename": "src/createStylesFromProps.ts",
"retrieved_chunk": " const [propName, value] = prop;\n // checks if prop is for styling\n if (typeof propName !== 'string' || !validateProp(propName)) {\n return prevValue;\n }\n const key = camelToKebabCase(propName.replace(PROP_PREFIX, ''));\n // checks if prop is something from customOverwrites\n if (isCustomOverwrite(prop)) {\n const [overwriteKey, overwriteValue] = prop;\n const themeValue = customOverwrites[overwriteKey](overwriteValue);",
"score": 8.227068463879894
},
{
"filename": "src/theme/customOverwrites.ts",
"retrieved_chunk": "import flattenObject from '../utils/flattenObject';\nimport COLORS from './color';\nconst flattenedColors = flattenObject(COLORS);\nexport const customOverwrites = {\n $backgroundColor: (value: keyof typeof flattenedColors) => flattenedColors[value],\n $color: (value: keyof typeof flattenedColors) => flattenedColors[value],\n};\ntype GetOverwriteValues<T> = {\n [P in keyof T]?: T[P] extends (...args: any) => string ? Parameters<T[P]>[0] : never;\n};",
"score": 8.09646036838044
},
{
"filename": "src/createStylesFromProps.ts",
"retrieved_chunk": " }\n return {\n ...prevValue,\n [key]: value,\n };\n }, {});\nexport default createStylesFromProps;",
"score": 7.213864713212909
}
] | typescript | export const prefixedPseudoElements = PSEUDO_ELEMENTS.map(pseudoEle => pseudoEle.replace('::', PROP_PREFIX)); |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find(
( | { name }) => name === token
); |
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),",
"score": 21.954077866041775
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "}\n/**\n * Shorthand to quickly get a well typed string date token configuration object.\n *\n * @param defaultValue - Override the values of the return object.\n * @returns DateTokenConfiguration<DateTokenType.string> - A well typed date token configuration object.\n */\nexport function createStringDateTokenConfiguration(\n\tdefaultValue: Partial<DateTokenConfiguration<DateTokenType.string>> = {}\n): DateTokenConfiguration<DateTokenType.string> {",
"score": 16.377229630152513
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\treturn isDefined(value) && value instanceof Object;\n}\n/**\n * Shorthand to quickly get a well typed number date token configuration object.\n *\n * @param defaultValue - Override the values of the return object.\n * @returns DateTokenConfiguration<DateTokenType.number> - A well typed date token configuration object.\n */\nexport function createNumberDateTokenConfiguration(\n\tdefaultValue: Partial<DateTokenConfiguration<DateTokenType.number>> = {}",
"score": 14.494461889151149
},
{
"filename": "src/types.ts",
"retrieved_chunk": ">;\n/**\n * String typed date token.\n */\ntype StringSpecific = Merge<\n\tCommonValues<DateTokenType.string>,\n\t{\n\t\t/**\n\t\t * The dictionary reference for the token\n\t\t */",
"score": 13.185229633743562
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " *\n * @param value - Date token configuration.\n * @returns typeguard.\n */\nexport function dateTokenConfigurationIsTypeString(\n\tvalue: DateTokenConfiguration\n): value is DateTokenConfiguration<DateTokenType.string> {\n\treturn value.type === DateTokenType.string;\n}\n/**",
"score": 13.165503965471757
}
] | typescript | { name }) => name === token
); |
import { PluginSettingTab } from "obsidian";
import { createApp, ref } from "vue";
import createVueI18nConfig from "~/i18n.config";
import VApp from "~/views/App.vue";
import type { App as ObsidianApp } from "obsidian";
import type AprilsAutomaticTimelinesPlugin from "~/main";
import type { AutoTimelineSettings, DateTokenConfiguration } from "./types";
import type { App as VueApp } from "vue";
import { createNumberDateTokenConfiguration } from "./utils";
/**
* Default key value relation for obsidian settings object
*/
export const SETTINGS_DEFAULT = {
metadataKeyEventStartDate: "aat-event-start-date",
metadataKeyEventEndDate: "aat-event-end-date",
metadataKeyEventTitleOverride: "aat-event-title",
metadataKeyEventBodyOverride: "aat-event-body",
metadataKeyEventPictureOverride: "aat-event-picture",
metadataKeyEventTimelineTag: "timelines",
noteInlineEventKey: "aat-inline-event",
markdownBlockTagsToFindSeparator: ",",
dateParserRegex: "(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)",
dateParserGroupPriority: "year,month,day",
dateDisplayFormat: "{day}/{month}/{year}",
lookForTagsForTimeline: false,
lookForInlineEventsInNotes: true,
applyAdditonalConditionFormatting: true,
dateTokenConfiguration: [
createNumberDateTokenConfiguration({ name: "year", minLeght: 4 }),
createNumberDateTokenConfiguration({ name: "month" }),
createNumberDateTokenConfiguration({ name: "day" }),
] as DateTokenConfiguration[],
};
export const __VUE_PROD_DEVTOOLS__ = true;
/**
* Class designed to display the inputs that allow the end user to change the default keys that are looked for when processing metadata in a single note.
*/
export class TimelineSettingTab extends PluginSettingTab {
plugin: AprilsAutomaticTimelinesPlugin;
vueApp: VueApp<Element> | null;
constructor(app: ObsidianApp, plugin: AprilsAutomaticTimelinesPlugin) {
super(app, plugin);
this.plugin = plugin;
this.vueApp = null;
}
display(): void {
this.containerEl.empty();
// TODO Read locale off obsidian.
| const i18n = createVueI18nConfig(); |
this.vueApp = createApp({
components: { VApp },
template: "<VApp :value='value' @update:value='save' />",
setup: () => {
const value = ref(this.plugin.settings);
return {
value,
save: async (payload: Partial<AutoTimelineSettings>) => {
this.plugin.settings = {
...this.plugin.settings,
...payload,
};
value.value = this.plugin.settings;
await this.plugin.saveSettings();
},
};
},
methods: {},
});
this.vueApp.use(i18n).mount(this.containerEl);
}
hide() {
if (!this.vueApp) return;
this.vueApp.unmount();
this.vueApp = null;
}
}
| src/settings.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/main.ts",
"retrieved_chunk": "export default class AprilsAutomaticTimelinesPlugin extends Plugin {\n\tsettings: AutoTimelineSettings;\n\t/**\n\t * The default onload method of a obsidian plugin\n\t * See the official documentation for more details\n\t */\n\tasync onload() {\n\t\tawait this.loadSettings();\n\t\tthis.registerMarkdownCodeBlockProcessor(\n\t\t\t\"aat-vertical\",",
"score": 28.79165083011673
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\tindex < this.settings.dateTokenConfiguration.length;\n\t\t\tindex++\n\t\t) {\n\t\t\tthis.settings.dateTokenConfiguration[index].formatting =\n\t\t\t\tthis.settings.dateTokenConfiguration[index].formatting || [];\n\t\t}\n\t\tthis.addSettingTab(new TimelineSettingTab(this.app, this));\n\t}\n\t/**\n\t * Saves the settings in obsidian.",
"score": 21.921366989316454
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t * Loads the saved settings from the local device and sets up the setting tabs in the plugin options.\n\t */\n\tasync loadSettings() {\n\t\tthis.settings = Object.assign(\n\t\t\t{},\n\t\t\tSETTINGS_DEFAULT,\n\t\t\tawait this.loadData()\n\t\t);\n\t\tfor (\n\t\t\tlet index = 0;",
"score": 21.35489622701649
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\tconst { app } = this;\n\t\tconst { tagsToFind, settingsOverride } =\n\t\t\tparseMarkdownBlockSource(source);\n\t\tconst finalSettings = { ...this.settings, ...settingsOverride };\n\t\tconst creationContext = setupTimelineCreation(\n\t\t\tapp,\n\t\t\telement,\n\t\t\tsourcePath,\n\t\t\tfinalSettings\n\t\t);",
"score": 20.363960048431384
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": " *\n * @param param0 - The context built for this timeline.\n * @param param0.elements - The HTMLElements exposed for this context.\n * @param param0.elements.cardListRootElement - The right side of the timeline, this is where the carads are spawned.\n * @param param0.file - The target note file.\n * @param param0.settings - The plugin's settings.\n * @param cardContent - The content of a single timeline card.\n */\nexport function createCardFromBuiltContext(\n\t{",
"score": 17.716616468278506
}
] | typescript | const i18n = createVueI18nConfig(); |
import { SETTINGS_DEFAULT } from "~/settings";
import { AutoTimelineSettings } from "./types";
import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils";
/**
* Fetches the tags to find and timeline specific settings override.
*
* @param source - The markdown code block source, a.k.a. the content inside the code block.
* @returns Partial settings to override the global ones.
*/
export function parseMarkdownBlockSource(source: string): {
readonly tagsToFind: string[];
readonly settingsOverride: Partial<AutoTimelineSettings>;
} {
const sourceEntries = source.split("\n");
if (!source.length)
return { tagsToFind: [] as string[], settingsOverride: {} } as const;
const tagsToFind = sourceEntries[0]
.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)
.map((e) => e.trim());
sourceEntries.shift();
return {
tagsToFind,
settingsOverride: sourceEntries.reduce((accumulator, element) => {
return {
...accumulator,
...parseSingleLine(element),
};
}, {} as Partial<AutoTimelineSettings>),
} as const;
}
type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];
const acceptedSettingsOverride = [
"dateDisplayFormat",
"applyAdditonalConditionFormatting",
] as const;
/**
* Checks if a given string is part of the settings keys that can be overriden.
*
* @param value - A given settings key.
* @returns the typeguard boolean `true` if the key is indeed overridable.
*/
function isOverridableSettingsKey(
value: string
): value is OverridableSettingKey {
// @ts-expect-error
return acceptedSettingsOverride.includes(value);
}
/**
* Will apply the needed formatting to a setting value based of it's key.
*
* @param key - The settings key.
* @param value - The value associated to this value.
* @returns Undefined if unvalid or the actual expected value.
*/
function formatValueFromKey(
key: string,
value: string
): AutoTimelineSettings[OverridableSettingKey] | undefined {
if (!isOverridableSettingsKey(key)) return undefined;
if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value;
if | (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) { |
const validBooleanStrings = ["true", "false"];
if (!validBooleanStrings.includes(value.toLocaleLowerCase()))
throw new Error(`${value} is supposed to be a boolean`);
return value.toLocaleLowerCase() === "true" ? true : false;
}
return undefined;
}
/**
* Parse a single line of the timeline markdown block content.
*
* @param line - The line to parse.
* @returns A potencialy partial settings object.
*/
function parseSingleLine(line: string): Partial<AutoTimelineSettings> {
const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i;
const matches = line.match(reg);
if (
!matches ||
!matches.groups ||
!isDefinedAsString(matches.groups.key) ||
!isDefined(matches.groups.value)
)
return {};
const key = matches.groups.key.trim();
const value = formatValueFromKey(key, matches.groups.value.trim());
if (!isDefined(value)) return {};
return { [key]: value };
}
| src/markdownBlockData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param cachedMetadata - cachedMetadata - Obsidians cachedMetadata object.\n * @param key - the sought after key in the obsidian metadata object.\n * @param type - The expected type of the key value.\n * @returns The metadata value assigned to the given key or null if unvalidated or missing.\n */\nexport function getMetadataKey<T extends \"string\" | \"number\" | \"boolean\">(\n\tcachedMetadata: MarkdownCodeBlockTimelineProcessingContext[\"cachedMetadata\"],\n\tkey: string,\n\ttype: T\n):",
"score": 38.19744827558398
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\t| (T extends \"string\" ? string : T extends \"number\" ? number : boolean)\n\t| undefined {\n\t// Bail if no formatter object or if the key is missing\n\tif (!cachedMetadata.frontmatter) return undefined;\n\treturn typeof cachedMetadata.frontmatter[key] === type\n\t\t? cachedMetadata.frontmatter[key]\n\t\t: undefined;\n}\n/**\n * Typeguard to check if a value is indeed defined.",
"score": 37.58683007164199
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "}\n/**\n * Typeguard to check if a value is an object of unknowed key values.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an object, `false` if not.\n */\nexport function isDefinedAsObject(\n\tvalue: unknown\n): value is { [key: string]: unknown } {",
"score": 32.99116783836413
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 27.634765998818988
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string",
"score": 26.35962484173255
}
] | typescript | (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) { |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output | = dateDisplayFormat.toString(); |
prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find(
({ name }) => name === token
);
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),",
"score": 24.89461654637352
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];\nconst acceptedSettingsOverride = [\n\t\"dateDisplayFormat\",\n\t\"applyAdditonalConditionFormatting\",\n] as const;\n/**\n * Checks if a given string is part of the settings keys that can be overriden.\n *\n * @param value - A given settings key.\n * @returns the typeguard boolean `true` if the key is indeed overridable.",
"score": 17.397290522715092
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 13.512396312624674
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " */\nexport function getTagsFromMetadataOrTagObject(\n\tsettings: AutoTimelineSettings,\n\tmetaData: Omit<FrontMatterCache, \"position\">,\n\ttags?: TagCache[]\n): string[] {\n\tlet output = [] as string[];\n\tconst timelineArray = metaData[settings.metadataKeyEventTimelineTag];\n\tif (isDefinedAsArray(timelineArray))\n\t\toutput = timelineArray.filter(isDefinedAsString);",
"score": 9.262477293855905
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t// Breakout earlier if we don't check the tags\n\tif (!settings.lookForTagsForTimeline) return output;\n\tif (isDefinedAsArray(tags))\n\t\toutput = output.concat(tags.map(({ tag }) => tag.substring(1)));\n\t// Tags in the frontmatter\n\tconst metadataInlineTags = metaData.tags;\n\tif (!isDefined(metadataInlineTags)) return output;\n\tif (isDefinedAsString(metadataInlineTags))\n\t\toutput = output.concat(\n\t\t\tmetadataInlineTags.split(\",\").map((e) => e.trim())",
"score": 8.809534054344361
}
] | typescript | = dateDisplayFormat.toString(); |
import { SETTINGS_DEFAULT } from "~/settings";
import { FnGetRangeData } from "./rangeData";
import { FnExtractCardData, getDataFromNoteMetadata } from "~/cardData";
import type { App, CachedMetadata, TFile } from "obsidian";
import type { Merge } from "ts-essentials";
/**
* @author https://stackoverflow.com/a/69756175
*/
export type PickByType<T, Value> = {
[P in keyof T as T[P] extends Value | undefined ? P : never]: T[P];
};
export type AutoTimelineSettings = typeof SETTINGS_DEFAULT;
/**
* The main bundle of data needed to build a timeline.
*/
export interface MarkdownCodeBlockTimelineProcessingContext {
/**
* Obsidian application context.
*/
app: App;
/**
* The plugins settings
*/
settings: AutoTimelineSettings;
/**
* The formatted metadata of a single note.
*/
cachedMetadata: CachedMetadata;
/**
* The file data of a single note.
*/
file: TFile;
/**
* The filepath of a single timeline.
*/
timelineFile: string;
/**
* Shorthand access to HTMLElements for the range timelines and the card list.
*/
elements: {
timelineRootElement: HTMLElement;
cardListRootElement: HTMLElement;
};
}
/**
* The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.
*/
export type CompleteCardContext = Exclude<
Awaited<ReturnType<typeof getDataFromNoteMetadata>>,
undefined
>;
/**
* The context extracted from a single note to create a single card in the timeline.
*/
export type CardContent = Awaited<ReturnType<FnExtractCardData>>;
/**
* The needed data to compute a range in a single timeline.
*/
export type | Range = ReturnType<FnGetRangeData>[number]; |
/**
* An abstract representation of a fantasy date.
* Given the fickle nature of story telling and how people will literally almost never stick to standard date formats
* We'll organise the dates in segments, let's take for example our human callendar
* The date will commonly be segmented in 3 parts year, month and day the abstract representation will equate to
* `[year, month, day]`
* Now if someone wants to make a more complex date system like `[cycle, moon, phase, day]` we can treat them the same when sorting and performing computing tasks on those dates.
* The only major limitation to this system is that all the dates must respect the same system.
*/
export type AbstractDate = number[];
/**
* Before formatting an abstract date, the end user can configure it's output display
* This DateToken type helps to determine what's the nature of a given token
* E.g. should it be displayed as a number or as a string ?
*/
export enum DateTokenType {
number = "NUMBER",
string = "STRING",
}
export const availableDateTokenTypeArray = Object.values(DateTokenType);
export enum Condition {
Greater = "GREATER",
Less = "LESS",
Equal = "EQUAL",
NotEqual = "NOTEQUAL",
GreaterOrEqual = "GREATEROREQUAL",
LessOrEqual = "LESSOREQUAL",
}
export const availableConditionArray = Object.values(Condition);
export type Evaluation<T extends number = number> = {
condition: Condition;
value: T;
};
export type AdditionalDateFormatting<T extends number = number> = {
evaluations: Evaluation<T>[];
/**
* Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.
*/
conditionsAreExclusive: boolean;
/**
* Use `{value}` to include the pre-formated output of the numerical value held.
*/
format: string;
};
/**
* The data used to compute the output of an abstract date based on it's type
*/
type CommonValues<T extends DateTokenType> = {
name: string;
type: T;
formatting: AdditionalDateFormatting[];
};
export type DateTokenConfiguration<T extends DateTokenType = DateTokenType> =
T extends DateTokenType.number
? NumberSpecific
: T extends DateTokenType.string
? StringSpecific
: StringSpecific | NumberSpecific;
/**
* Number typed date token.
*/
type NumberSpecific = Merge<
CommonValues<DateTokenType.number>,
{
/**
* The minimum ammount of digits when displaying the date
*/
minLeght: number;
displayWhenZero: boolean;
hideSign: boolean;
}
>;
/**
* String typed date token.
*/
type StringSpecific = Merge<
CommonValues<DateTokenType.string>,
{
/**
* The dictionary reference for the token
*/
dictionary: string[];
}
>;
| src/types.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": " * Will compute all the data needed to build ranges in the timeline.\n *\n * @param collection - The complete collection of relevant data gathered from notes.\n * @returns the needed data to build ranges in the timeline.\n */\nexport function getAllRangeData(collection: CompleteCardContext[]) {\n\tif (!collection.length) return [];\n\treturn collection.reduce(\n\t\t(accumulator, relatedCardData, index) => {\n\t\t\tconst {",
"score": 28.193318061802234
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tcontext,\n\t} as const;\n}\n/**\n * Provides additional context for the creation cards in the DOM but reads it from the body\n *\n * @param body - The extracted body for a single event card.\n * @param context - Timeline generic context.\n * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.",
"score": 27.949833714566374
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t};\n\t\t\treadonly index: number;\n\t\t\treadonly targetPosition: number;\n\t\t\treadonly cardRelativeTopPosition: number;\n\t\t}[]\n\t);\n}\nexport type FnGetRangeData = typeof getAllRangeData;\n/**\n * Finds the end position in pixel relative to the top of the timeline root element for the give endDate of a range.",
"score": 24.590694609402878
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t(source, element, context) => {\n\t\t\t\tthis.run(source, element, context);\n\t\t\t}\n\t\t);\n\t}\n\tonunload() {}\n\t/**\n\t * Main runtime function to process a single timeline.\n\t *\n\t * @param source - The content found in the markdown block.",
"score": 24.55424141805444
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 23.818126859386282
}
] | typescript | Range = ReturnType<FnGetRangeData>[number]; |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
prioArray.forEach((token, index) => {
| const configuration = dateTokenConfiguration.find(
({ name }) => name === token
); |
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),",
"score": 26.103180623770697
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "}\n/**\n * Shorthand to quickly get a well typed string date token configuration object.\n *\n * @param defaultValue - Override the values of the return object.\n * @returns DateTokenConfiguration<DateTokenType.string> - A well typed date token configuration object.\n */\nexport function createStringDateTokenConfiguration(\n\tdefaultValue: Partial<DateTokenConfiguration<DateTokenType.string>> = {}\n): DateTokenConfiguration<DateTokenType.string> {",
"score": 16.377229630152513
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\treturn isDefined(value) && value instanceof Object;\n}\n/**\n * Shorthand to quickly get a well typed number date token configuration object.\n *\n * @param defaultValue - Override the values of the return object.\n * @returns DateTokenConfiguration<DateTokenType.number> - A well typed date token configuration object.\n */\nexport function createNumberDateTokenConfiguration(\n\tdefaultValue: Partial<DateTokenConfiguration<DateTokenType.number>> = {}",
"score": 14.494461889151149
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];\nconst acceptedSettingsOverride = [\n\t\"dateDisplayFormat\",\n\t\"applyAdditonalConditionFormatting\",\n] as const;\n/**\n * Checks if a given string is part of the settings keys that can be overriden.\n *\n * @param value - A given settings key.\n * @returns the typeguard boolean `true` if the key is indeed overridable.",
"score": 13.976026394937598
},
{
"filename": "src/types.ts",
"retrieved_chunk": ">;\n/**\n * String typed date token.\n */\ntype StringSpecific = Merge<\n\tCommonValues<DateTokenType.string>,\n\t{\n\t\t/**\n\t\t * The dictionary reference for the token\n\t\t */",
"score": 13.185229633743562
}
] | typescript | const configuration = dateTokenConfiguration.find(
({ name }) => name === token
); |
import {
isDefined,
findLastIndex,
lerp,
inLerp,
getChildAtIndexInHTMLElement,
compareAbstractDates,
} from "~/utils";
import type { CompleteCardContext, AbstractDate } from "~/types";
/**
* Will compute all the data needed to build ranges in the timeline.
*
* @param collection - The complete collection of relevant data gathered from notes.
* @returns the needed data to build ranges in the timeline.
*/
export function getAllRangeData(collection: CompleteCardContext[]) {
if (!collection.length) return [];
return collection.reduce(
(accumulator, relatedCardData, index) => {
const {
context: {
elements: { timelineRootElement, cardListRootElement },
},
cardData: { startDate, endDate },
} = relatedCardData;
if (!isDefined(startDate) || !isDefined(endDate))
return accumulator;
if (
endDate !== true &&
compareAbstractDates(endDate, startDate) < 0
)
return accumulator;
const timelineLength = timelineRootElement.offsetHeight;
const targetCard = cardListRootElement.children.item(
index
) as HTMLElement | null;
// Error handling but should not happen
if (!targetCard) return accumulator;
const cardRelativeTopPosition = targetCard.offsetTop;
let targetPosition: number;
if (endDate === true) targetPosition = timelineLength;
else
targetPosition = findEndPositionForDate(
endDate,
collection.slice(index),
timelineLength,
cardListRootElement,
index
);
accumulator.push({
relatedCardData: {
...relatedCardData,
cardData: {
...relatedCardData.cardData,
endDate,
startDate,
},
},
targetPosition,
cardRelativeTopPosition,
index,
} as const);
return accumulator;
},
[] as {
readonly relatedCardData: CompleteCardContext & {
cardData: CompleteCardContext["cardData"] & {
| startDate: AbstractDate; |
endDate: AbstractDate | true;
};
};
readonly index: number;
readonly targetPosition: number;
readonly cardRelativeTopPosition: number;
}[]
);
}
export type FnGetRangeData = typeof getAllRangeData;
/**
* Finds the end position in pixel relative to the top of the timeline root element for the give endDate of a range.
*
* @param date - The target endDate to position on the timeline.
* @param collection - The collection of cards part of the same timeline.
* @param timelineLength - The length in pixel of the timeline.
* @param rootElement - The root HTMLElement of the cardList.
* @param indexOffset - Since the date is already sorted by date we can save a little time by skipping all the elements before.
* @returns The expected position relative to the top of the timeline container for this date range.
*/
export function findEndPositionForDate(
date: AbstractDate,
collection: CompleteCardContext[],
timelineLength: number,
rootElement: HTMLElement,
indexOffset: number
): number {
if (collection.length <= 1) return timelineLength;
try {
const { start, end } = findBoundaries(
date,
collection,
rootElement,
indexOffset
);
const [inLerpStart, inLerpEnd, targetInLerpDate] = getInLerpValues(
start.date,
end.date,
date
);
const t = inLerp(inLerpStart, inLerpEnd, targetInLerpDate);
return lerp(start.top, end.top, t);
} catch (_) {
return timelineLength;
}
}
/**
* Gets the values to compute the inlerp needed for range gutter renders.
*
* @param a - The start date
* @param b - The end date
* @param c - The date in between
* @returns the first non equal member of a - b when compared from left to right, also returns the same member from c.
*/
export function getInLerpValues(
a: AbstractDate,
b: AbstractDate,
c: AbstractDate
): [number, number, number] {
for (let index = 0; index < a.length; index++) {
if (a[index] === b[index]) continue;
return [a[index], b[index], c[index]];
}
return [0, 1, 1];
}
type Boundary = { date: AbstractDate; top: number };
/**
* Find the position of the last card having a lower start date and the first card with a higher start date relative to the endDate of the evaluated range.
*
* @param date - The target endDate to position on the timeline.
* @param collection - The collection of cards part of the same timeline.
* @param rootElement - The root HTMLElement of the cardList.
* @param indexOffset - Since the date is already sorted by date we can save a little time by skipping all the elements before.
* @returns The start and end boundaries of the target end date.
*/
export function findBoundaries(
date: AbstractDate,
collection: CompleteCardContext[],
rootElement: HTMLElement,
indexOffset: number
): { start: Boundary; end: Boundary } {
const firstOverIndex = collection.findIndex(({ cardData: { startDate } }) =>
isDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false
);
if (firstOverIndex === -1)
throw new Error(
"No first over found - Can't draw range since there are no other two start date to referrence it's position"
);
const firstLastUnderIndex = findLastIndex(
collection,
({ cardData: { startDate } }) =>
isDefined(startDate)
? compareAbstractDates(startDate, date) <= 0
: false
);
if (firstLastUnderIndex === -1)
throw new Error(
"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members"
);
const lastUnderIndex = collection.findIndex(
({ cardData: { startDate } }, index) => {
return (
compareAbstractDates(
startDate,
collection[firstLastUnderIndex].cardData.startDate
) === 0
);
}
);
if (lastUnderIndex === -1)
throw new Error(
"No last under found - Can't draw range since there are no other two start date to referrence it's position"
);
const startElement = getChildAtIndexInHTMLElement(
rootElement,
lastUnderIndex + indexOffset
);
const startDate = collection[lastUnderIndex].cardData
.startDate as AbstractDate;
const startIsMoreThanOneCardAway = lastUnderIndex > 1;
const shouldOffsetStartToBottomOfCard =
startIsMoreThanOneCardAway &&
compareAbstractDates(startDate, date) !== 0;
return {
start: {
top:
startElement.offsetTop +
(shouldOffsetStartToBottomOfCard
? startElement.innerHeight
: 0),
date: startDate,
},
end: {
top: getChildAtIndexInHTMLElement(
rootElement,
firstOverIndex + indexOffset
).offsetTop,
date: collection[firstOverIndex].cardData.startDate as AbstractDate,
},
};
}
| src/rangeData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||",
"score": 16.99962607351836
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t\t\t},\n\t\t},\n\t\ttargetPosition,\n\t\tcardRelativeTopPosition,\n\t\tindex,\n\t}: Range,\n\toffset: number,\n\trootElelement: HTMLElement\n) {\n\tconst el = createElementShort(",
"score": 14.098567329648146
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\tawait getDataFromNoteBody(body, context, tagsToFind)\n\t\t\t).filter(isDefined);\n\t\t\tif (!inlineEvents.length) continue;\n\t\t\tevents.push(...inlineEvents);\n\t\t}\n\t\tevents.sort(\n\t\t\t(\n\t\t\t\t{ cardData: { startDate: a, endDate: aE } },\n\t\t\t\t{ cardData: { startDate: b, endDate: bE } }\n\t\t\t) => {",
"score": 13.56710762545799
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treturn {\n\t\ttagsToFind,\n\t\tsettingsOverride: sourceEntries.reduce((accumulator, element) => {\n\t\t\treturn {\n\t\t\t\t...accumulator,\n\t\t\t\t...parseSingleLine(element),\n\t\t\t};\n\t\t}, {} as Partial<AutoTimelineSettings>),\n\t} as const;\n}",
"score": 12.959353022673529
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treadonly tagsToFind: string[];\n\treadonly settingsOverride: Partial<AutoTimelineSettings>;\n} {\n\tconst sourceEntries = source.split(\"\\n\");\n\tif (!source.length)\n\t\treturn { tagsToFind: [] as string[], settingsOverride: {} } as const;\n\tconst tagsToFind = sourceEntries[0]\n\t\t.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)\n\t\t.map((e) => e.trim());\n\tsourceEntries.shift();",
"score": 12.808755373176085
}
] | typescript | startDate: AbstractDate; |
import { SETTINGS_DEFAULT } from "~/settings";
import { AutoTimelineSettings } from "./types";
import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils";
/**
* Fetches the tags to find and timeline specific settings override.
*
* @param source - The markdown code block source, a.k.a. the content inside the code block.
* @returns Partial settings to override the global ones.
*/
export function parseMarkdownBlockSource(source: string): {
readonly tagsToFind: string[];
readonly settingsOverride: Partial<AutoTimelineSettings>;
} {
const sourceEntries = source.split("\n");
if (!source.length)
return { tagsToFind: [] as string[], settingsOverride: {} } as const;
const tagsToFind = sourceEntries[0]
.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)
.map((e) => e.trim());
sourceEntries.shift();
return {
tagsToFind,
settingsOverride: sourceEntries.reduce((accumulator, element) => {
return {
...accumulator,
...parseSingleLine(element),
};
}, {} as Partial<AutoTimelineSettings>),
} as const;
}
type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];
const acceptedSettingsOverride = [
"dateDisplayFormat",
"applyAdditonalConditionFormatting",
] as const;
/**
* Checks if a given string is part of the settings keys that can be overriden.
*
* @param value - A given settings key.
* @returns the typeguard boolean `true` if the key is indeed overridable.
*/
function isOverridableSettingsKey(
value: string
): value is OverridableSettingKey {
// @ts-expect-error
return acceptedSettingsOverride.includes(value);
}
/**
* Will apply the needed formatting to a setting value based of it's key.
*
* @param key - The settings key.
* @param value - The value associated to this value.
* @returns Undefined if unvalid or the actual expected value.
*/
function formatValueFromKey(
key: string,
value: string
): AutoTimelineSettings[OverridableSettingKey] | undefined {
if (!isOverridableSettingsKey(key)) return undefined;
if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value;
if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) {
const validBooleanStrings = ["true", "false"];
if (!validBooleanStrings.includes(value.toLocaleLowerCase()))
throw new Error(`${value} is supposed to be a boolean`);
return value.toLocaleLowerCase() === "true" ? true : false;
}
return undefined;
}
/**
* Parse a single line of the timeline markdown block content.
*
* @param line - The line to parse.
* @returns A potencialy partial settings object.
*/
function parseSingleLine(line: string): Partial<AutoTimelineSettings> {
const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i;
const matches = line.match(reg);
if (
!matches ||
!matches.groups ||
!isDefinedAsString(matches.groups.key) ||
| !isDefined(matches.groups.value)
)
return {}; |
const key = matches.groups.key.trim();
const value = formatValueFromKey(key, matches.groups.value.trim());
if (!isDefined(value)) return {};
return { [key]: value };
}
| src/markdownBlockData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tmetadataString: string,\n\treg: RegExp | string\n): AbstractDate | undefined {\n\tconst matches = metadataString.match(reg);\n\tif (!matches || !matches.groups) return undefined;\n\tconst { groups } = matches;\n\tconst output = groupsToCheck.reduce((accumulator, groupName) => {\n\t\tconst value = Number(groups[groupName]);\n\t\t// In the case of a faulty regex given by the user in the settings\n\t\tif (!isNaN(value)) accumulator.push(value);",
"score": 73.45983083786815
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\t\"gi\"\n\t);\n\tconst originalFrontmatter = context.cachedMetadata.frontmatter;\n\tconst matches = body.match(inlineEventBlockRegExp);\n\tif (!matches) return [];\n\tmatches.unshift();\n\tconst output: CompleteCardContext[] = [];\n\tfor (const block of matches) {\n\t\tconst sanitizedBlock = block.split(\"\\n\");\n\t\tsanitizedBlock.shift();",
"score": 44.27140687972229
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t} = app;\n\tconst override = metadata?.[metadataKeyEventPictureOverride];\n\tif (override) return override;\n\tconst internalLinkMatch = rawFileText.match(/!\\[\\[(?<src>.*)\\]\\]/);\n\tconst matchs =\n\t\tinternalLinkMatch || rawFileText.match(/!\\[.*\\]\\((?<src>.*)\\)/);\n\tif (!matchs || !matchs.groups || !matchs.groups.src) return null;\n\tif (internalLinkMatch) {\n\t\t// https://github.com/obsidianmd/obsidian-releases/pull/1882#issuecomment-1512952295\n\t\tconst file = getFirstLinkpathDest.bind(app.metadataCache)(",
"score": 21.17486156865623
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t\t\tmatchs.groups.src,\n\t\t\tcurrentFile.path\n\t\t) satisfies TFile | null;\n\t\tif (file instanceof TFile) return vault.getResourcePath(file);\n\t\t// Thanks https://github.com/joethei\n\t\treturn null;\n\t} else return encodeURI(matchs.groups.src);\n}\n/**\n * Given a metadata key it'll try to parse the associated data as an `AbstractDate` and return it",
"score": 20.84620632456203
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "}\n/**\n * Typeguard to check if a value is an object of unknowed key values.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an object, `false` if not.\n */\nexport function isDefinedAsObject(\n\tvalue: unknown\n): value is { [key: string]: unknown } {",
"score": 17.856970303954718
}
] | typescript | !isDefined(matches.groups.value)
)
return {}; |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
| const prioArray = dateParserGroupPriority.split(","); |
let output = dateDisplayFormat.toString();
prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find(
({ name }) => name === token
);
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),",
"score": 20.7455137886446
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];\nconst acceptedSettingsOverride = [\n\t\"dateDisplayFormat\",\n\t\"applyAdditonalConditionFormatting\",\n] as const;\n/**\n * Checks if a given string is part of the settings keys that can be overriden.\n *\n * @param value - A given settings key.\n * @returns the typeguard boolean `true` if the key is indeed overridable.",
"score": 13.68609745531946
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 13.512396312624674
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": " */\nexport function getDateText(\n\t{ startDate, endDate }: Pick<CardContent, \"startDate\" | \"endDate\">,\n\tsettings: AutoTimelineSettings\n): string {\n\tif (!isDefined(startDate)) return \"Start date missing\";\n\tconst formatedStart = formatAbstractDate(startDate, settings);\n\tif (!isDefined(endDate)) return formatedStart;\n\treturn `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;\n}",
"score": 10.559276679366583
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treadonly tagsToFind: string[];\n\treadonly settingsOverride: Partial<AutoTimelineSettings>;\n} {\n\tconst sourceEntries = source.split(\"\\n\");\n\tif (!source.length)\n\t\treturn { tagsToFind: [] as string[], settingsOverride: {} } as const;\n\tconst tagsToFind = sourceEntries[0]\n\t\t.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)\n\t\t.map((e) => e.trim());\n\tsourceEntries.shift();",
"score": 9.356727747827279
}
] | typescript | const prioArray = dateParserGroupPriority.split(","); |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find(
({ name }) => name === token
);
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
| applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string { |
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": "}\n/**\n * Shorthand to quickly get a well typed string date token configuration object.\n *\n * @param defaultValue - Override the values of the return object.\n * @returns DateTokenConfiguration<DateTokenType.string> - A well typed date token configuration object.\n */\nexport function createStringDateTokenConfiguration(\n\tdefaultValue: Partial<DateTokenConfiguration<DateTokenType.string>> = {}\n): DateTokenConfiguration<DateTokenType.string> {",
"score": 34.3268797873544
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\treturn isDefined(value) && value instanceof Object;\n}\n/**\n * Shorthand to quickly get a well typed number date token configuration object.\n *\n * @param defaultValue - Override the values of the return object.\n * @returns DateTokenConfiguration<DateTokenType.number> - A well typed date token configuration object.\n */\nexport function createNumberDateTokenConfiguration(\n\tdefaultValue: Partial<DateTokenConfiguration<DateTokenType.number>> = {}",
"score": 30.088943941890697
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " *\n * @param value - Date token configuration.\n * @returns typeguard.\n */\nexport function dateTokenConfigurationIsTypeString(\n\tvalue: DateTokenConfiguration\n): value is DateTokenConfiguration<DateTokenType.string> {\n\treturn value.type === DateTokenType.string;\n}\n/**",
"score": 29.690963244524266
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "/**\n * Parse a string based off user date extract settings.\n *\n * @param groupsToCheck - The token names to check.\n * @param metadataString - The actual extracted data from the frontmatter.\n * @param reg - The user defined regex to apply.\n * @returns The parsed abstract date or nothing.\n */\nexport function parseAbstractDate(\n\tgroupsToCheck: string[],",
"score": 28.745422894801738
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " * Narrow type down to specific subtype for DateTokenConfigurations.\n *\n * @param value - Date token configuration.\n * @returns typeguard.\n */\nexport function dateTokenConfigurationIsTypeNumber(\n\tvalue: DateTokenConfiguration\n): value is DateTokenConfiguration<DateTokenType.number> {\n\treturn value.type === DateTokenType.number;\n}",
"score": 27.46434377906634
}
] | typescript | applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string { |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find(
| ({ name }) => name === token
); |
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),",
"score": 26.103180623770697
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "}\n/**\n * Shorthand to quickly get a well typed string date token configuration object.\n *\n * @param defaultValue - Override the values of the return object.\n * @returns DateTokenConfiguration<DateTokenType.string> - A well typed date token configuration object.\n */\nexport function createStringDateTokenConfiguration(\n\tdefaultValue: Partial<DateTokenConfiguration<DateTokenType.string>> = {}\n): DateTokenConfiguration<DateTokenType.string> {",
"score": 16.377229630152513
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\treturn isDefined(value) && value instanceof Object;\n}\n/**\n * Shorthand to quickly get a well typed number date token configuration object.\n *\n * @param defaultValue - Override the values of the return object.\n * @returns DateTokenConfiguration<DateTokenType.number> - A well typed date token configuration object.\n */\nexport function createNumberDateTokenConfiguration(\n\tdefaultValue: Partial<DateTokenConfiguration<DateTokenType.number>> = {}",
"score": 14.494461889151149
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];\nconst acceptedSettingsOverride = [\n\t\"dateDisplayFormat\",\n\t\"applyAdditonalConditionFormatting\",\n] as const;\n/**\n * Checks if a given string is part of the settings keys that can be overriden.\n *\n * @param value - A given settings key.\n * @returns the typeguard boolean `true` if the key is indeed overridable.",
"score": 13.976026394937598
},
{
"filename": "src/types.ts",
"retrieved_chunk": ">;\n/**\n * String typed date token.\n */\ntype StringSpecific = Merge<\n\tCommonValues<DateTokenType.string>,\n\t{\n\t\t/**\n\t\t * The dictionary reference for the token\n\t\t */",
"score": 13.185229633743562
}
] | typescript | ({ name }) => name === token
); |
import { getMetadataKey, isDefined, isDefinedAsObject } from "~/utils";
import type {
MarkdownCodeBlockTimelineProcessingContext,
CompleteCardContext,
} from "~/types";
import { parse } from "yaml";
import {
getAbstractDateFromMetadata,
getBodyFromContextOrDocument,
getImageUrlFromContextOrDocument,
getTagsFromMetadataOrTagObject,
} from "./cardDataExtraction";
/**
* A un-changeable key used to check if a note is eligeable for render.
*/
const RENDER_GREENLIGHT_METADATA_KEY = ["aat-render-enabled"];
/**
* Provides additional context for the creation cards in the DOM.
*
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteMetadata(
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
) {
const { cachedMetadata, settings } = context;
const { frontmatter: metaData, tags } = cachedMetadata;
if (!metaData) return undefined;
if (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))
return undefined;
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
metaData,
tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;
return {
cardData: await extractCardData(context),
context,
} as const;
}
/**
* Provides additional context for the creation cards in the DOM but reads it from the body
*
* @param body - The extracted body for a single event card.
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteBody(
body: string | undefined | null,
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
): Promise<CompleteCardContext[]> {
const { settings } = context;
if (!body) return [];
const inlineEventBlockRegExp = new RegExp(
`%%${settings.noteInlineEventKey}\n(((\\s|\\d|[a-z]|-)*):(.*)\n)*%%`,
"gi"
);
const originalFrontmatter = context.cachedMetadata.frontmatter;
const matches = body.match(inlineEventBlockRegExp);
if (!matches) return [];
matches.unshift();
const output: CompleteCardContext[] = [];
for (const block of matches) {
const sanitizedBlock = block.split("\n");
sanitizedBlock.shift();
sanitizedBlock.pop();
const fakeFrontmatter = parse(sanitizedBlock.join("\n")); // this actually works lmao
// Replace frontmatter with newly built fake one. Just to re-use all the existing code.
context.cachedMetadata.frontmatter = fakeFrontmatter;
| if (!isDefinedAsObject(fakeFrontmatter)) continue; |
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
fakeFrontmatter,
context.cachedMetadata.tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;
const matchPositionInBody = body.indexOf(block);
output.push({
cardData: await extractCardData(
context,
matchPositionInBody !== -1
? body.slice(matchPositionInBody + block.length)
: undefined
),
context,
});
}
context.cachedMetadata.frontmatter = originalFrontmatter;
return output;
}
/**
* Checks if the extracted tags match at least one of the tags to find.
*
* @param timelineTags - The extracted tags from the note.
* @param tagsToFind - The tags to find.
* @returns `true` if valid.
*/
function extractedTagsAreValid(
timelineTags: string[],
tagsToFind: string[]
): boolean {
return timelineTags.some((tag) => tagsToFind.includes(tag));
}
/**
* Get the content of a card from a note. This function will parse the raw text content of a note and format it.
*
* @param context - Timeline generic context.
* @param rawFileContent - If you already have it, will avoid reading the file again.
* @returns The extracted data to create a card from a note.
*/
export async function extractCardData(
context: MarkdownCodeBlockTimelineProcessingContext,
rawFileContent?: string
) {
const { file, cachedMetadata: c, settings } = context;
const fileTitle =
c.frontmatter?.[settings.metadataKeyEventTitleOverride] ||
file.basename;
rawFileContent = rawFileContent || (await file.vault.cachedRead(file));
return {
title: fileTitle as string,
body: getBodyFromContextOrDocument(rawFileContent, context),
imageURL: getImageUrlFromContextOrDocument(rawFileContent, context),
startDate: getAbstractDateFromMetadata(
context,
settings.metadataKeyEventStartDate
),
endDate:
getAbstractDateFromMetadata(
context,
settings.metadataKeyEventEndDate
) ??
(isDefined(
getMetadataKey(c, settings.metadataKeyEventEndDate, "boolean")
)
? true
: undefined),
} as const;
}
export type FnExtractCardData = typeof extractCardData;
| src/cardData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t\tsettings: { metadataKeyEventBodyOverride },\n\t} = context;\n\tconst overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;\n\tif (!rawFileText.length || overrideBody) return overrideBody;\n\tconst rawTextArray = rawFileText.split(\"\\n\");\n\trawTextArray.shift();\n\tconst processedArray = rawTextArray.slice(rawTextArray.indexOf(\"---\") + 1);\n\tconst finalString = processedArray.join(\"\\n\").trim();\n\treturn finalString;\n}",
"score": 25.74569422325357
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": " *\n * @param line - The line to parse.\n * @returns A potencialy partial settings object.\n */\nfunction parseSingleLine(line: string): Partial<AutoTimelineSettings> {\n\tconst reg = /((?<key>(\\s|\\d|[a-z])*):(?<value>.*))/i;\n\tconst matches = line.match(reg);\n\tif (\n\t\t!matches ||\n\t\t!matches.groups ||",
"score": 19.84128263687854
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t// Breakout earlier if we don't check the tags\n\tif (!settings.lookForTagsForTimeline) return output;\n\tif (isDefinedAsArray(tags))\n\t\toutput = output.concat(tags.map(({ tag }) => tag.substring(1)));\n\t// Tags in the frontmatter\n\tconst metadataInlineTags = metaData.tags;\n\tif (!isDefined(metadataInlineTags)) return output;\n\tif (isDefinedAsString(metadataInlineTags))\n\t\toutput = output.concat(\n\t\t\tmetadataInlineTags.split(\",\").map((e) => e.trim())",
"score": 19.580388479169144
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tmetadataString: string,\n\treg: RegExp | string\n): AbstractDate | undefined {\n\tconst matches = metadataString.match(reg);\n\tif (!matches || !matches.groups) return undefined;\n\tconst { groups } = matches;\n\tconst output = groupsToCheck.reduce((accumulator, groupName) => {\n\t\tconst value = Number(groups[groupName]);\n\t\t// In the case of a faulty regex given by the user in the settings\n\t\tif (!isNaN(value)) accumulator.push(value);",
"score": 18.717869982648114
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treadonly tagsToFind: string[];\n\treadonly settingsOverride: Partial<AutoTimelineSettings>;\n} {\n\tconst sourceEntries = source.split(\"\\n\");\n\tif (!source.length)\n\t\treturn { tagsToFind: [] as string[], settingsOverride: {} } as const;\n\tconst tagsToFind = sourceEntries[0]\n\t\t.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)\n\t\t.map((e) => e.trim());\n\tsourceEntries.shift();",
"score": 18.110664915630256
}
] | typescript | if (!isDefinedAsObject(fakeFrontmatter)) continue; |
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { getClientIp } from "./utils";
import { NextRequest } from "next/server";
import {
upstashToken,
upstashUrl,
enableUpstash,
upstashBanEnabled,
upstashBanDuration,
maxRequests,
requestsWindow,
} from "@/configs/upstash";
const isValidUpstash = () => {
if (!upstashUrl) {
console.error("UPSTASH_URL is missing from your environment variables.");
}
if (!upstashToken) {
console.error("UPSTASH_TOKEN is missing from your environment variables.");
}
return upstashUrl !== "" && upstashToken != "";
};
export const redisClient = new Redis({
url: upstashUrl,
token: upstashToken,
});
export const ratelimit = new Ratelimit({
redis: redisClient,
limiter: Ratelimit.slidingWindow(maxRequests, requestsWindow),
});
export const isRatelimited = async (request: NextRequest) => {
if (!enableUpstash) return false;
// Check if upstash variables are set correctly
const validUpstash = isValidUpstash();
if (!validUpstash) return false;
try {
const | identifier = getClientIp(request); |
if (!identifier) return false;
const result = await ratelimit.limit(identifier);
if (result.success) return false;
// Ban user if ratelimit exceeded
if (upstashBanEnabled) {
await redisClient.setex(
`ban:${identifier}`,
upstashBanDuration,
"banned"
);
}
return true;
} catch (error: any) {
console.error(error.message);
return false;
}
};
| src/lib/rate-limiter.ts | riad-azz-instagram-video-downloader-78513ff | [
{
"filename": "src/lib/utils.ts",
"retrieved_chunk": "};\nexport const isJsonResponse = (response: Response) => {\n const contentType = response.headers.get(\"content-type\");\n return contentType && contentType.includes(\"application/json\");\n};\nexport const getClientIp = (request: NextRequest) => {\n let ip = request.ip ?? request.headers.get(\"x-real-ip\");\n const forwardedFor = request.headers.get(\"x-forwarded-for\");\n if (!ip && forwardedFor) {\n ip = forwardedFor.split(\",\").at(0) ?? null;",
"score": 24.44059933213652
},
{
"filename": "src/middleware.ts",
"retrieved_chunk": " path.startsWith(\"/og.png\") ||\n path.startsWith(\"/robot.txt\") ||\n path.startsWith(\"/site.webmanifest\")\n );\n};\nexport async function middleware(request: NextRequest) {\n const requestPath = request.nextUrl.pathname;\n const country = request.geo?.country ?? \"Country\";\n if (isStaticPath(requestPath)) {\n return NextResponse.next();",
"score": 24.36043327160696
},
{
"filename": "src/middleware.ts",
"retrieved_chunk": "import { NextRequest, NextResponse } from \"next/server\";\nimport { upstashBanDuration } from \"./configs/upstash\";\nimport { enableServerAPI } from \"./configs/instagram\";\nimport { getClientIp } from \"@/lib/utils\";\nimport { isRatelimited } from \"./lib/rate-limiter\";\nconst isStaticPath = (path: string) => {\n return (\n path.startsWith(\"/_next\") ||\n path.startsWith(\"/images\") ||\n path.startsWith(\"/favicon.ico\") ||",
"score": 21.423361196376355
},
{
"filename": "src/__tests__/ratelimit.test.ts",
"retrieved_chunk": "// Check if the environment variables are defined\ndescribe(\"upstash-env-variables\", () => {\n it(\"should have a USE_UPSTASH variable\", () => {\n expect(process.env.USE_UPSTASH).toBeDefined();\n });\n it(\"should have a UPSTASH_URL variable\", () => {\n expect(process.env.UPSTASH_URL).toBeDefined();\n });\n it(\"should have a UPSTASH_TOKEN variable\", () => {\n expect(process.env.UPSTASH_TOKEN).toBeDefined();",
"score": 21.07788041799193
},
{
"filename": "src/lib/utils.ts",
"retrieved_chunk": " const successResponse = makeSuccessResponse<T>(response.data);\n return successResponse;\n } catch (error: any) {\n const axiosError: AxiosError = error;\n if (axiosError.response) {\n return makeErrorResponse(axiosError.message);\n } else if (axiosError.request) {\n console.log(\"Request Error:\", axiosError.request);\n return makeErrorResponse(\"Request timeout, please try again.\");\n } else {",
"score": 20.32947229096927
}
] | typescript | identifier = getClientIp(request); |
"use client";
import { useState, FormEvent } from "react";
import { DownloadButton } from "./DownloadButton";
import { Exception, ClientException } from "@/exceptions";
import { fetchVideoInfoAction } from "@/lib/instagram/actions";
import { APIResponse, VideoInfo } from "@/types";
const validateInput = (postUrl: string) => {
if (!postUrl) {
throw new ClientException("Instagram URL was not provided");
}
if (!postUrl.includes("instagram.com/")) {
throw new ClientException("Invalid URL does not contain Instagram domain");
}
if (!postUrl.startsWith("https://")) {
throw new ClientException(
'Invalid URL it should start with "https://www.instagram.com..."'
);
}
const postRegex =
/^https:\/\/(?:www\.)?instagram\.com\/p\/([a-zA-Z0-9_-]+)\/?/;
const reelRegex =
/^https:\/\/(?:www\.)?instagram\.com\/reels?\/([a-zA-Z0-9_-]+)\/?/;
if (!postRegex.test(postUrl) && !reelRegex.test(postUrl)) {
throw new ClientException("URL does not match Instagram post or reel");
}
};
const downloadVideo = async (filename: string, downloadUrl: any) => {
try {
await fetch(downloadUrl)
.then((response) => response.blob())
.then((blob) => {
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.target = "_blank";
a.href = blobUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
});
} catch (error) {
const a = document.createElement("a");
a.target = "_blank";
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
console.log(error);
}
};
const fetchVideo = async (postUrl: string) => {
const response: APIResponse<VideoInfo> = await fetchVideoInfoAction(postUrl);
if (response.status === "error") {
throw new ClientException(response.message);
}
const { filename, videoUrl } = response.data;
await downloadVideo(filename, videoUrl);
return true;
};
export default function InstagramForm() {
const [postUrl, setPostUrl] = useState("");
const [errorMsg, setErrorMsg] = useState("");
const [isLoading, setIsLoading] = useState(false);
function handleError(error: any) {
if (error instanceof Exception) {
setErrorMsg(error.message);
} else {
console.error(error);
setErrorMsg(
"Something went wrong, if this problem persists contact the developer."
);
}
setIsLoading(false);
}
async function handleSubmit(e: FormEvent) {
e.preventDefault();
setIsLoading(true);
setErrorMsg("");
try {
validateInput(postUrl);
} catch (error: any) {
return handleError(error);
}
try {
const isSuccess = await fetchVideo(postUrl);
if (isSuccess) setErrorMsg("");
} catch (error: any) {
return handleError(error);
}
setIsLoading(false);
}
return (
<>
{errorMsg !== "" && (
<div className="mb-1 text-sm text-red-500 md:text-base">{errorMsg}</div>
)}
<form
className="flex flex-col items-center gap-4 motion-safe:animate-[animate-up_1.5s_ease-in-out_1] md:flex-row md:gap-2"
onSubmit={handleSubmit}
>
<label htmlFor="url-input" className="sr-only">
instagram URL input
</label>
<input
id="url-input"
type="url"
value={postUrl}
autoFocus={true}
onChange={(e) => setPostUrl(e.target.value)}
placeholder="e.g. https://www.instagram.com/p/CGh4a0iASGS"
aria-label="Instagram video download URL input"
title="Instagram video download URL input"
className="w-full rounded border border-slate-100 px-2 py-3 placeholder-gray-400/80 drop-shadow-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-none dark:bg-gray-700 dark:text-white dark:placeholder-gray-400"
/>
< | DownloadButton isLoading={isLoading} />
</form>
</>
); |
}
| src/components/instagram/InstagramForm.tsx | riad-azz-instagram-video-downloader-78513ff | [
{
"filename": "src/components/instagram/DownloadButton.tsx",
"retrieved_chunk": " type=\"submit\"\n className=\"inline-flex items-center gap-2 rounded border border-slate-100 bg-white px-5 py-3.5 text-sm tracking-wide drop-shadow-lg transition-transform focus:outline-none focus:ring-2 focus:ring-blue-500 active:scale-95 dark:border-none dark:bg-gray-700 max-md:w-full max-md:justify-center\"\n disabled={isLoading}\n >\n {isLoading && (\n <>\n <Icons.loading />\n <span>Fetching</span>\n </>\n )}",
"score": 121.67036634147846
},
{
"filename": "src/components/navigation/MenuButton.tsx",
"retrieved_chunk": " className=\"order-last ml-3 inline-flex items-center rounded-lg border border-gray-300 p-2 text-sm text-gray-500 hover:bg-gray-100 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600 md:hidden\"\n aria-controls=\"navbar-dropdown\"\n aria-expanded=\"false\"\n >\n <span className=\"sr-only\">Open navbar menu</span>\n <Icons.menu />\n </button>\n );\n};",
"score": 90.17326312733567
},
{
"filename": "src/components/navigation/ThemeButton.tsx",
"retrieved_chunk": " <button\n title=\"Toggle Theme\"\n onClick={() => toggleTheme()}\n className=\"flex items-center justify-between rounded-lg border border-gray-300 bg-transparent p-2.5 text-sm font-medium text-gray-900 hover:bg-gray-100 dark:border-gray-600 dark:text-white dark:hover:bg-gray-700 dark:focus:ring-gray-600 md:border-0\"\n >\n <Icons.themeMode />\n </button>\n );\n};",
"score": 87.1293077267506
},
{
"filename": "src/components/navigation/MobileMenuLink.tsx",
"retrieved_chunk": "}) => {\n return (\n <li>\n <Link\n href={href}\n target={target}\n className=\"flex w-full items-center gap-4 rounded-lg border border-gray-300 bg-white px-5 py-2 font-medium text-gray-900 hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-800 dark:text-white dark:hover:border-gray-600 dark:hover:bg-gray-700\"\n >\n {children}\n </Link>",
"score": 78.20509588752836
},
{
"filename": "src/components/navigation/NavLink.tsx",
"retrieved_chunk": " href={href}\n target={target}\n className=\"flex items-center gap-2 rounded bg-white px-3 py-2 font-medium text-gray-900 hover:bg-gray-100 dark:bg-gray-800 dark:text-white dark:hover:bg-gray-700\"\n >\n {children}\n </Link>\n </li>\n );\n};",
"score": 64.53466585016398
}
] | typescript | DownloadButton isLoading={isLoading} />
</form>
</>
); |
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { getClientIp } from "./utils";
import { NextRequest } from "next/server";
import {
upstashToken,
upstashUrl,
enableUpstash,
upstashBanEnabled,
upstashBanDuration,
maxRequests,
requestsWindow,
} from "@/configs/upstash";
const isValidUpstash = () => {
if (!upstashUrl) {
console.error("UPSTASH_URL is missing from your environment variables.");
}
if (!upstashToken) {
console.error("UPSTASH_TOKEN is missing from your environment variables.");
}
return upstashUrl !== "" && upstashToken != "";
};
export const redisClient = new Redis({
url: upstashUrl,
token: upstashToken,
});
export const ratelimit = new Ratelimit({
redis: redisClient,
limiter: Ratelimit.slidingWindow(maxRequests, requestsWindow),
});
export const isRatelimited = async (request: NextRequest) => {
if (!enableUpstash) return false;
// Check if upstash variables are set correctly
const validUpstash = isValidUpstash();
if (!validUpstash) return false;
try {
| const identifier = getClientIp(request); |
if (!identifier) return false;
const result = await ratelimit.limit(identifier);
if (result.success) return false;
// Ban user if ratelimit exceeded
if (upstashBanEnabled) {
await redisClient.setex(
`ban:${identifier}`,
upstashBanDuration,
"banned"
);
}
return true;
} catch (error: any) {
console.error(error.message);
return false;
}
};
| src/lib/rate-limiter.ts | riad-azz-instagram-video-downloader-78513ff | [
{
"filename": "src/lib/utils.ts",
"retrieved_chunk": "};\nexport const isJsonResponse = (response: Response) => {\n const contentType = response.headers.get(\"content-type\");\n return contentType && contentType.includes(\"application/json\");\n};\nexport const getClientIp = (request: NextRequest) => {\n let ip = request.ip ?? request.headers.get(\"x-real-ip\");\n const forwardedFor = request.headers.get(\"x-forwarded-for\");\n if (!ip && forwardedFor) {\n ip = forwardedFor.split(\",\").at(0) ?? null;",
"score": 24.44059933213652
},
{
"filename": "src/middleware.ts",
"retrieved_chunk": " path.startsWith(\"/og.png\") ||\n path.startsWith(\"/robot.txt\") ||\n path.startsWith(\"/site.webmanifest\")\n );\n};\nexport async function middleware(request: NextRequest) {\n const requestPath = request.nextUrl.pathname;\n const country = request.geo?.country ?? \"Country\";\n if (isStaticPath(requestPath)) {\n return NextResponse.next();",
"score": 24.36043327160696
},
{
"filename": "src/middleware.ts",
"retrieved_chunk": "import { NextRequest, NextResponse } from \"next/server\";\nimport { upstashBanDuration } from \"./configs/upstash\";\nimport { enableServerAPI } from \"./configs/instagram\";\nimport { getClientIp } from \"@/lib/utils\";\nimport { isRatelimited } from \"./lib/rate-limiter\";\nconst isStaticPath = (path: string) => {\n return (\n path.startsWith(\"/_next\") ||\n path.startsWith(\"/images\") ||\n path.startsWith(\"/favicon.ico\") ||",
"score": 21.423361196376355
},
{
"filename": "src/__tests__/ratelimit.test.ts",
"retrieved_chunk": "// Check if the environment variables are defined\ndescribe(\"upstash-env-variables\", () => {\n it(\"should have a USE_UPSTASH variable\", () => {\n expect(process.env.USE_UPSTASH).toBeDefined();\n });\n it(\"should have a UPSTASH_URL variable\", () => {\n expect(process.env.UPSTASH_URL).toBeDefined();\n });\n it(\"should have a UPSTASH_TOKEN variable\", () => {\n expect(process.env.UPSTASH_TOKEN).toBeDefined();",
"score": 21.07788041799193
},
{
"filename": "src/lib/utils.ts",
"retrieved_chunk": " const successResponse = makeSuccessResponse<T>(response.data);\n return successResponse;\n } catch (error: any) {\n const axiosError: AxiosError = error;\n if (axiosError.response) {\n return makeErrorResponse(axiosError.message);\n } else if (axiosError.request) {\n console.log(\"Request Error:\", axiosError.request);\n return makeErrorResponse(\"Request timeout, please try again.\");\n } else {",
"score": 20.32947229096927
}
] | typescript | const identifier = getClientIp(request); |
import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from "@prisma/client";
import { prisma } from "../../../prisma/client";
export class GetPedidoPorCpfUseCase {
async getPedidoPorCpf(numero: string): Promise<any | null> {
if (numero.length === 11) {
const clienteCpf = await prisma.cliente.findFirst({
where: {
cpf: numero
}
});
if (clienteCpf) {
const pedido = await prisma.pedido.findMany({
where: {
id_cliente: clienteCpf.id_cliente
},
include: {
cliente: {
select: {
nome_completo: true,
cpf: true
}
},
pedido_status: {
select: {
status_pedido: true,
status_erro: true
}
},
nota_fiscal: {
select: {
numero_nota: true
}
},
pagamento: {
select: {
tipo_pagamento: true,
parcela: true
}
},
produto: {
select: {
nome_produto: true,
quantidade: true
}
}
}
});
if (!pedido) {
return null;
}
const pedidosFormatados = pedido.map(( | pedido) => ({ |
numero: pedido.numero,
status_pedido: pedido.pedido_status.status_pedido,
status_erro: pedido.pedido_status.status_erro,
numero_nota_fiscal: pedido.nota_fiscal.numero_nota,
data_pedido_realizado: pedido.data_pedido_realizado,
nome_cliente: pedido.cliente.nome_completo,
cpf_cliente: pedido.cliente.cpf,
tipo_pagamento: pedido.pagamento.tipo_pagamento,
}));
return pedidosFormatados;
}
}
}
}
| src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts | Iguu42-node-project-FC-0cd6618 | [
{
"filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts",
"retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {",
"score": 13.782703177340508
},
{
"filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts",
"retrieved_chunk": " })\n if (!pedidos) {\n return null\n }\n const pedidosFormatados = pedidos.map(pedido => ({\n status_pedido: pedido.pedido_status.status_pedido,\n status_erro: pedido.pedido_status.status_erro,\n pedido: pedido.cliente.cpf,\n numero_nota_fiscal: pedido.nota_fiscal.numero_nota,\n data_pedido_realizado: pedido.data_pedido_realizado,",
"score": 13.646558800034954
},
{
"filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts",
"retrieved_chunk": " });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {\n return total + (produto.valor * produto.quantidade);\n }, 0);\n return {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,\n numeroDoPedido: pedido.numero,",
"score": 10.550700796584795
},
{
"filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts",
"retrieved_chunk": " });\n if (!pedido) {\n return null;\n }\n const produtosFormatados: { nome: string; referencia: string; descricao: string; quantidade: number; valor_produto: number; valor_total_produto: number; }[] = [];\n pedido.produto.forEach((produto) => {\n const produtoFormatado = {\n nome: produto.nome_produto,\n referencia: produto.referencia,\n descricao: produto.descricao,",
"score": 8.899152355928248
},
{
"filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts",
"retrieved_chunk": " nome_cliente: pedido.cliente.nome_completo,\n tipo_pagamento: pedido.pagamento.tipo_pagamento,\n // valor_e_parcela: `${pedido.pagamento.parcela}x - R$${pedido.produto.valor}`,\n // nome_produto: pedido.produto.nome_produto,\n // quantidade_produto: pedido.produto.quantidade\n }))\n return pedidosFormatados\n }\n}",
"score": 7.682108898508433
}
] | typescript | pedido) => ({ |
import {
pedido,
pedido_status,
nota_fiscal,
pagamento,
produto,
cliente
} from '@prisma/client'
import { prisma } from '../../../prisma/client'
export class GetPedidosDataUseCase {
async allPedidosData(data: String): Promise<any[] | null> {
const pedidos = await prisma.pedido.findMany({
where: {
data_pedido_realizado: {
gte: new Date(`${data}`),
lt: new Date(`${data}T23:59:59Z`)
}
},
include: {
cliente: {
select: {
nome_completo: true,
cpf: true
}
},
pedido_status: {
select: {
status_pedido: true,
status_erro: true
}
},
nota_fiscal: {
select: {
numero_nota: true
}
},
pagamento: {
select: {
tipo_pagamento: true,
parcela: true
}
},
produto: {
select: {
nome_produto: true,
quantidade: true,
valor: true
}
}
}
})
if (!pedidos) {
return null
}
| const pedidosFormatados = pedidos.map(pedido => ({ |
status_pedido: pedido.pedido_status.status_pedido,
status_erro: pedido.pedido_status.status_erro,
pedido: pedido.cliente.cpf,
numero_nota_fiscal: pedido.nota_fiscal.numero_nota,
data_pedido_realizado: pedido.data_pedido_realizado,
nome_cliente: pedido.cliente.nome_completo,
tipo_pagamento: pedido.pagamento.tipo_pagamento,
// valor_e_parcela: `${pedido.pagamento.parcela}x - R$${pedido.produto.valor}`,
// nome_produto: pedido.produto.nome_produto,
// quantidade_produto: pedido.produto.quantidade
}))
return pedidosFormatados
}
}
| src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts | Iguu42-node-project-FC-0cd6618 | [
{
"filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts",
"retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {",
"score": 19.067666362712288
},
{
"filename": "src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts",
"retrieved_chunk": " select: {\n nome_produto: true,\n quantidade: true\n }\n }\n }\n });\n if (!pedido) {\n return null;\n }",
"score": 14.1281363110367
},
{
"filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts",
"retrieved_chunk": " });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {\n return total + (produto.valor * produto.quantidade);\n }, 0);\n return {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,\n numeroDoPedido: pedido.numero,",
"score": 12.530681012345584
},
{
"filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts",
"retrieved_chunk": " status_erro: true\n }\n },\n produto: {\n select: {\n valor: true,\n quantidade: true\n }\n },\n }",
"score": 11.20975368769372
},
{
"filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts",
"retrieved_chunk": " referencia: true,\n descricao: true,\n quantidade: true,\n valor: true,\n }\n },\n pagamento: {\n select: {\n tipo_pagamento: true,\n parcela: true,",
"score": 10.756419615690985
}
] | typescript | const pedidosFormatados = pedidos.map(pedido => ({ |
import {
isDefinedAsString,
isDefined,
isDefinedAsArray,
getMetadataKey,
parseAbstractDate,
} from "~/utils";
import { FrontMatterCache, TagCache, TFile } from "obsidian";
import type {
AutoTimelineSettings,
AbstractDate,
MarkdownCodeBlockTimelineProcessingContext,
} from "~/types";
/**
* Returns a list of tags based off plugin settings, note frontmatter and note tags.
*
* @param settings - The plugins settings.
* @param metaData - The frontematter cache.
* @param tags - Potencial tags.
* @returns A list of tags to look for in a note.
*/
export function getTagsFromMetadataOrTagObject(
settings: AutoTimelineSettings,
metaData: Omit<FrontMatterCache, "position">,
tags?: TagCache[]
): string[] {
let output = [] as string[];
const timelineArray = metaData[settings.metadataKeyEventTimelineTag];
if (isDefinedAsArray(timelineArray))
output = timelineArray.filter(isDefinedAsString);
// Breakout earlier if we don't check the tags
if (!settings.lookForTagsForTimeline) return output;
if (isDefinedAsArray(tags))
output = output.concat(tags.map(({ tag }) => tag.substring(1)));
// Tags in the frontmatter
const metadataInlineTags = metaData.tags;
if (!isDefined(metadataInlineTags)) return output;
if (isDefinedAsString(metadataInlineTags))
output = output.concat(
metadataInlineTags.split(",").map((e) => e.trim())
);
if (isDefinedAsArray(metadataInlineTags))
output = output.concat(metadataInlineTags.filter(isDefinedAsString));
// .substring called to remove the initial `#` in the notes tags
return output;
}
/**
* Extract the body from the raw text of a note.
* After extraction most markdown tokens will be removed and links will be sanitized aswell and wrapped into bold tags for clearner display.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the body of a given card or null if none was found.
*/
export function getBodyFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
settings: { | metadataKeyEventBodyOverride },
} = context; |
const overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;
if (!rawFileText.length || overrideBody) return overrideBody;
const rawTextArray = rawFileText.split("\n");
rawTextArray.shift();
const processedArray = rawTextArray.slice(rawTextArray.indexOf("---") + 1);
const finalString = processedArray.join("\n").trim();
return finalString;
}
/**
* Extract the first image from the raw markdown in a note.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the URL of the image to be displayed in a card or null if none where found.
*/
export function getImageUrlFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
file: currentFile,
app,
settings: { metadataKeyEventPictureOverride },
} = context;
const {
vault,
metadataCache: { getFirstLinkpathDest },
} = app;
const override = metadata?.[metadataKeyEventPictureOverride];
if (override) return override;
const internalLinkMatch = rawFileText.match(/!\[\[(?<src>.*)\]\]/);
const matchs =
internalLinkMatch || rawFileText.match(/!\[.*\]\((?<src>.*)\)/);
if (!matchs || !matchs.groups || !matchs.groups.src) return null;
if (internalLinkMatch) {
// https://github.com/obsidianmd/obsidian-releases/pull/1882#issuecomment-1512952295
const file = getFirstLinkpathDest.bind(app.metadataCache)(
matchs.groups.src,
currentFile.path
) satisfies TFile | null;
if (file instanceof TFile) return vault.getResourcePath(file);
// Thanks https://github.com/joethei
return null;
} else return encodeURI(matchs.groups.src);
}
/**
* Given a metadata key it'll try to parse the associated data as an `AbstractDate` and return it
*
* @param param0 - Timeline generic context.
* @param param0.cachedMetadata - The cached metadata from a note.
* @param param0.settings - the plugin's settings.
* @param key - The target lookup key in the notes metadata object.
* @returns the abstract date representation or undefined.
*/
export function getAbstractDateFromMetadata(
{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,
key: string
): AbstractDate | undefined {
const groupsToCheck = settings.dateParserGroupPriority.split(",");
const numberValue = getMetadataKey(cachedMetadata, key, "number");
if (isDefined(numberValue)) {
const additionalContentForNumberOnlydate = [
...Array(Math.max(0, groupsToCheck.length - 1)),
].map(() => 0);
return [numberValue, ...additionalContentForNumberOnlydate];
}
const stringValue = getMetadataKey(cachedMetadata, key, "string");
if (!stringValue) return undefined;
return parseAbstractDate(
groupsToCheck,
stringValue,
settings.dateParserRegex
);
}
| src/cardDataExtraction.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 17.788880849974923
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,",
"score": 17.01633943153632
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param cachedMetadata - cachedMetadata - Obsidians cachedMetadata object.\n * @param key - the sought after key in the obsidian metadata object.\n * @param type - The expected type of the key value.\n * @returns The metadata value assigned to the given key or null if unvalidated or missing.\n */\nexport function getMetadataKey<T extends \"string\" | \"number\" | \"boolean\">(\n\tcachedMetadata: MarkdownCodeBlockTimelineProcessingContext[\"cachedMetadata\"],\n\tkey: string,\n\ttype: T\n):",
"score": 16.774611734043372
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tconst fileTitle =\n\t\tc.frontmatter?.[settings.metadataKeyEventTitleOverride] ||\n\t\tfile.basename;\n\trawFileContent = rawFileContent || (await file.vault.cachedRead(file));\n\treturn {\n\t\ttitle: fileTitle as string,\n\t\tbody: getBodyFromContextOrDocument(rawFileContent, context),\n\t\timageURL: getImageUrlFromContextOrDocument(rawFileContent, context),\n\t\tstartDate: getAbstractDateFromMetadata(\n\t\t\tcontext,",
"score": 16.43403495331232
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 14.813360746263593
}
] | typescript | metadataKeyEventBodyOverride },
} = context; |
import {
pedido,
pedido_status,
nota_fiscal,
pagamento,
produto,
cliente
} from '@prisma/client'
import { prisma } from '../../../prisma/client'
export class GetPedidosDataUseCase {
async allPedidosData(data: String): Promise<any[] | null> {
const pedidos = await prisma.pedido.findMany({
where: {
data_pedido_realizado: {
gte: new Date(`${data}`),
lt: new Date(`${data}T23:59:59Z`)
}
},
include: {
cliente: {
select: {
nome_completo: true,
cpf: true
}
},
pedido_status: {
select: {
status_pedido: true,
status_erro: true
}
},
nota_fiscal: {
select: {
numero_nota: true
}
},
pagamento: {
select: {
tipo_pagamento: true,
parcela: true
}
},
produto: {
select: {
nome_produto: true,
quantidade: true,
valor: true
}
}
}
})
if (!pedidos) {
return null
}
const pedidosFormatados = pedidos.map | (pedido => ({ |
status_pedido: pedido.pedido_status.status_pedido,
status_erro: pedido.pedido_status.status_erro,
pedido: pedido.cliente.cpf,
numero_nota_fiscal: pedido.nota_fiscal.numero_nota,
data_pedido_realizado: pedido.data_pedido_realizado,
nome_cliente: pedido.cliente.nome_completo,
tipo_pagamento: pedido.pagamento.tipo_pagamento,
// valor_e_parcela: `${pedido.pagamento.parcela}x - R$${pedido.produto.valor}`,
// nome_produto: pedido.produto.nome_produto,
// quantidade_produto: pedido.produto.quantidade
}))
return pedidosFormatados
}
}
| src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts | Iguu42-node-project-FC-0cd6618 | [
{
"filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts",
"retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {",
"score": 15.012182828139565
},
{
"filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts",
"retrieved_chunk": " });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {\n return total + (produto.valor * produto.quantidade);\n }, 0);\n return {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,\n numeroDoPedido: pedido.numero,",
"score": 10.871433668407427
},
{
"filename": "src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts",
"retrieved_chunk": " select: {\n nome_produto: true,\n quantidade: true\n }\n }\n }\n });\n if (!pedido) {\n return null;\n }",
"score": 9.078221489903507
},
{
"filename": "src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts",
"retrieved_chunk": " const pedidosFormatados = pedido.map((pedido) => ({\n numero: pedido.numero,\n status_pedido: pedido.pedido_status.status_pedido,\n status_erro: pedido.pedido_status.status_erro,\n numero_nota_fiscal: pedido.nota_fiscal.numero_nota,\n data_pedido_realizado: pedido.data_pedido_realizado,\n nome_cliente: pedido.cliente.nome_completo,\n cpf_cliente: pedido.cliente.cpf,\n tipo_pagamento: pedido.pagamento.tipo_pagamento,\n }));",
"score": 6.344187890052709
},
{
"filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts",
"retrieved_chunk": " status_erro: true\n }\n },\n produto: {\n select: {\n valor: true,\n quantidade: true\n }\n },\n }",
"score": 5.8236271635774415
}
] | typescript | (pedido => ({ |
import {
isDefinedAsString,
isDefined,
isDefinedAsArray,
getMetadataKey,
parseAbstractDate,
} from "~/utils";
import { FrontMatterCache, TagCache, TFile } from "obsidian";
import type {
AutoTimelineSettings,
AbstractDate,
MarkdownCodeBlockTimelineProcessingContext,
} from "~/types";
/**
* Returns a list of tags based off plugin settings, note frontmatter and note tags.
*
* @param settings - The plugins settings.
* @param metaData - The frontematter cache.
* @param tags - Potencial tags.
* @returns A list of tags to look for in a note.
*/
export function getTagsFromMetadataOrTagObject(
settings: AutoTimelineSettings,
metaData: Omit<FrontMatterCache, "position">,
tags?: TagCache[]
): string[] {
let output = [] as string[];
const timelineArray = metaData[settings.metadataKeyEventTimelineTag];
if (isDefinedAsArray(timelineArray))
output = timelineArray.filter(isDefinedAsString);
// Breakout earlier if we don't check the tags
if (!settings.lookForTagsForTimeline) return output;
if (isDefinedAsArray(tags))
output = output.concat(tags.map(({ tag }) => tag.substring(1)));
// Tags in the frontmatter
const metadataInlineTags = metaData.tags;
if (!isDefined(metadataInlineTags)) return output;
if (isDefinedAsString(metadataInlineTags))
output = output.concat(
metadataInlineTags.split(",").map((e) => e.trim())
);
if (isDefinedAsArray(metadataInlineTags))
output = output.concat(metadataInlineTags.filter(isDefinedAsString));
// .substring called to remove the initial `#` in the notes tags
return output;
}
/**
* Extract the body from the raw text of a note.
* After extraction most markdown tokens will be removed and links will be sanitized aswell and wrapped into bold tags for clearner display.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the body of a given card or null if none was found.
*/
export function getBodyFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
settings: { metadataKeyEventBodyOverride },
} = context;
const overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;
if (!rawFileText.length || overrideBody) return overrideBody;
const rawTextArray = rawFileText.split("\n");
rawTextArray.shift();
const processedArray = rawTextArray.slice(rawTextArray.indexOf("---") + 1);
const finalString = processedArray.join("\n").trim();
return finalString;
}
/**
* Extract the first image from the raw markdown in a note.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the URL of the image to be displayed in a card or null if none where found.
*/
export function getImageUrlFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
file: currentFile,
app,
settings: { | metadataKeyEventPictureOverride },
} = context; |
const {
vault,
metadataCache: { getFirstLinkpathDest },
} = app;
const override = metadata?.[metadataKeyEventPictureOverride];
if (override) return override;
const internalLinkMatch = rawFileText.match(/!\[\[(?<src>.*)\]\]/);
const matchs =
internalLinkMatch || rawFileText.match(/!\[.*\]\((?<src>.*)\)/);
if (!matchs || !matchs.groups || !matchs.groups.src) return null;
if (internalLinkMatch) {
// https://github.com/obsidianmd/obsidian-releases/pull/1882#issuecomment-1512952295
const file = getFirstLinkpathDest.bind(app.metadataCache)(
matchs.groups.src,
currentFile.path
) satisfies TFile | null;
if (file instanceof TFile) return vault.getResourcePath(file);
// Thanks https://github.com/joethei
return null;
} else return encodeURI(matchs.groups.src);
}
/**
* Given a metadata key it'll try to parse the associated data as an `AbstractDate` and return it
*
* @param param0 - Timeline generic context.
* @param param0.cachedMetadata - The cached metadata from a note.
* @param param0.settings - the plugin's settings.
* @param key - The target lookup key in the notes metadata object.
* @returns the abstract date representation or undefined.
*/
export function getAbstractDateFromMetadata(
{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,
key: string
): AbstractDate | undefined {
const groupsToCheck = settings.dateParserGroupPriority.split(",");
const numberValue = getMetadataKey(cachedMetadata, key, "number");
if (isDefined(numberValue)) {
const additionalContentForNumberOnlydate = [
...Array(Math.max(0, groupsToCheck.length - 1)),
].map(() => 0);
return [numberValue, ...additionalContentForNumberOnlydate];
}
const stringValue = getMetadataKey(cachedMetadata, key, "string");
if (!stringValue) return undefined;
return parseAbstractDate(
groupsToCheck,
stringValue,
settings.dateParserRegex
);
}
| src/cardDataExtraction.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 16.514855994584185
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 16.304786640982297
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tconst fileTitle =\n\t\tc.frontmatter?.[settings.metadataKeyEventTitleOverride] ||\n\t\tfile.basename;\n\trawFileContent = rawFileContent || (await file.vault.cachedRead(file));\n\treturn {\n\t\ttitle: fileTitle as string,\n\t\tbody: getBodyFromContextOrDocument(rawFileContent, context),\n\t\timageURL: getImageUrlFromContextOrDocument(rawFileContent, context),\n\t\tstartDate: getAbstractDateFromMetadata(\n\t\t\tcontext,",
"score": 16.299712874460894
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param cachedMetadata - cachedMetadata - Obsidians cachedMetadata object.\n * @param key - the sought after key in the obsidian metadata object.\n * @param type - The expected type of the key value.\n * @returns The metadata value assigned to the given key or null if unvalidated or missing.\n */\nexport function getMetadataKey<T extends \"string\" | \"number\" | \"boolean\">(\n\tcachedMetadata: MarkdownCodeBlockTimelineProcessingContext[\"cachedMetadata\"],\n\tkey: string,\n\ttype: T\n):",
"score": 15.441807269939233
},
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": "\t\tconst cachedMetadata = metadataCache.getFileCache(file);\n\t\tif (cachedMetadata)\n\t\t\taccumulator.push({\n\t\t\t\tapp,\n\t\t\t\tsettings,\n\t\t\t\ttimelineFile,\n\t\t\t\tfile,\n\t\t\t\tcachedMetadata,\n\t\t\t\telements: {\n\t\t\t\t\ttimelineRootElement,",
"score": 15.379113828751256
}
] | typescript | metadataKeyEventPictureOverride },
} = context; |
import { getMetadataKey, isDefined, isDefinedAsObject } from "~/utils";
import type {
MarkdownCodeBlockTimelineProcessingContext,
CompleteCardContext,
} from "~/types";
import { parse } from "yaml";
import {
getAbstractDateFromMetadata,
getBodyFromContextOrDocument,
getImageUrlFromContextOrDocument,
getTagsFromMetadataOrTagObject,
} from "./cardDataExtraction";
/**
* A un-changeable key used to check if a note is eligeable for render.
*/
const RENDER_GREENLIGHT_METADATA_KEY = ["aat-render-enabled"];
/**
* Provides additional context for the creation cards in the DOM.
*
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteMetadata(
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
) {
const { cachedMetadata, settings } = context;
const { frontmatter: metaData, tags } = cachedMetadata;
if (!metaData) return undefined;
if (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))
return undefined;
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
metaData,
tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;
return {
cardData: await extractCardData(context),
context,
} as const;
}
/**
* Provides additional context for the creation cards in the DOM but reads it from the body
*
* @param body - The extracted body for a single event card.
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteBody(
body: string | undefined | null,
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
): Promise<CompleteCardContext[]> {
const { settings } = context;
if (!body) return [];
const inlineEventBlockRegExp = new RegExp(
`%%${settings.noteInlineEventKey}\n(((\\s|\\d|[a-z]|-)*):(.*)\n)*%%`,
"gi"
);
const originalFrontmatter = context.cachedMetadata.frontmatter;
const matches = body.match(inlineEventBlockRegExp);
if (!matches) return [];
matches.unshift();
const output: CompleteCardContext[] = [];
for (const block of matches) {
const sanitizedBlock = block.split("\n");
sanitizedBlock.shift();
sanitizedBlock.pop();
const fakeFrontmatter = parse(sanitizedBlock.join("\n")); // this actually works lmao
// Replace frontmatter with newly built fake one. Just to re-use all the existing code.
context.cachedMetadata.frontmatter = fakeFrontmatter;
if (!isDefinedAsObject(fakeFrontmatter)) continue;
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
fakeFrontmatter,
context.cachedMetadata.tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;
const matchPositionInBody = body.indexOf(block);
output.push({
cardData: await extractCardData(
context,
matchPositionInBody !== -1
? body.slice(matchPositionInBody + block.length)
: undefined
),
context,
});
}
context.cachedMetadata.frontmatter = originalFrontmatter;
return output;
}
/**
* Checks if the extracted tags match at least one of the tags to find.
*
* @param timelineTags - The extracted tags from the note.
* @param tagsToFind - The tags to find.
* @returns `true` if valid.
*/
function extractedTagsAreValid(
timelineTags: string[],
tagsToFind: string[]
): boolean {
return timelineTags.some((tag) => tagsToFind.includes(tag));
}
/**
* Get the content of a card from a note. This function will parse the raw text content of a note and format it.
*
* @param context - Timeline generic context.
* @param rawFileContent - If you already have it, will avoid reading the file again.
* @returns The extracted data to create a card from a note.
*/
export async function extractCardData(
context: MarkdownCodeBlockTimelineProcessingContext,
rawFileContent?: string
) {
const { file, cachedMetadata: c, settings } = context;
const fileTitle =
| c.frontmatter?.[settings.metadataKeyEventTitleOverride] ||
file.basename; |
rawFileContent = rawFileContent || (await file.vault.cachedRead(file));
return {
title: fileTitle as string,
body: getBodyFromContextOrDocument(rawFileContent, context),
imageURL: getImageUrlFromContextOrDocument(rawFileContent, context),
startDate: getAbstractDateFromMetadata(
context,
settings.metadataKeyEventStartDate
),
endDate:
getAbstractDateFromMetadata(
context,
settings.metadataKeyEventEndDate
) ??
(isDefined(
getMetadataKey(c, settings.metadataKeyEventEndDate, "boolean")
)
? true
: undefined),
} as const;
}
export type FnExtractCardData = typeof extractCardData;
| src/cardData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): string | null {\n\tconst {\n\t\tcachedMetadata: { frontmatter: metadata },\n\t\tfile: currentFile,\n\t\tapp,\n\t\tsettings: { metadataKeyEventPictureOverride },\n\t} = context;\n\tconst {\n\t\tvault,\n\t\tmetadataCache: { getFirstLinkpathDest },",
"score": 25.072020090170902
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " * @param rawFileText - The text content of a obsidian note.\n * @param context - Timeline generic context.\n * @returns the body of a given card or null if none was found.\n */\nexport function getBodyFromContextOrDocument(\n\trawFileText: string,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext\n): string | null {\n\tconst {\n\t\tcachedMetadata: { frontmatter: metadata },",
"score": 24.579444759723636
},
{
"filename": "src/types.ts",
"retrieved_chunk": ">;\n/**\n * The context extracted from a single note to create a single card in the timeline.\n */\nexport type CardContent = Awaited<ReturnType<FnExtractCardData>>;\n/**\n * The needed data to compute a range in a single timeline.\n */\nexport type Range = ReturnType<FnGetRangeData>[number];\n/**",
"score": 23.285265586746355
},
{
"filename": "src/types.ts",
"retrieved_chunk": "\t/**\n\t * The plugins settings\n\t */\n\tsettings: AutoTimelineSettings;\n\t/**\n\t * The formatted metadata of a single note.\n\t */\n\tcachedMetadata: CachedMetadata;\n\t/**\n\t * The file data of a single note.",
"score": 23.255822293509254
},
{
"filename": "src/types.ts",
"retrieved_chunk": "\t\ttimelineRootElement: HTMLElement;\n\t\tcardListRootElement: HTMLElement;\n\t};\n}\n/**\n * The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.\n */\nexport type CompleteCardContext = Exclude<\n\tAwaited<ReturnType<typeof getDataFromNoteMetadata>>,\n\tundefined",
"score": 21.64392867861649
}
] | typescript | c.frontmatter?.[settings.metadataKeyEventTitleOverride] ||
file.basename; |
import {
isDefinedAsString,
isDefined,
isDefinedAsArray,
getMetadataKey,
parseAbstractDate,
} from "~/utils";
import { FrontMatterCache, TagCache, TFile } from "obsidian";
import type {
AutoTimelineSettings,
AbstractDate,
MarkdownCodeBlockTimelineProcessingContext,
} from "~/types";
/**
* Returns a list of tags based off plugin settings, note frontmatter and note tags.
*
* @param settings - The plugins settings.
* @param metaData - The frontematter cache.
* @param tags - Potencial tags.
* @returns A list of tags to look for in a note.
*/
export function getTagsFromMetadataOrTagObject(
settings: AutoTimelineSettings,
metaData: Omit<FrontMatterCache, "position">,
tags?: TagCache[]
): string[] {
let output = [] as string[];
const timelineArray = metaData[settings.metadataKeyEventTimelineTag];
if (isDefinedAsArray(timelineArray))
output = timelineArray.filter(isDefinedAsString);
// Breakout earlier if we don't check the tags
if (!settings.lookForTagsForTimeline) return output;
if (isDefinedAsArray(tags))
output = output.concat(tags.map(({ tag }) => tag.substring(1)));
// Tags in the frontmatter
const metadataInlineTags = metaData.tags;
if (!isDefined(metadataInlineTags)) return output;
if (isDefinedAsString(metadataInlineTags))
output = output.concat(
metadataInlineTags.split(",").map((e) => e.trim())
);
if (isDefinedAsArray(metadataInlineTags))
output = output.concat(metadataInlineTags.filter(isDefinedAsString));
// .substring called to remove the initial `#` in the notes tags
return output;
}
/**
* Extract the body from the raw text of a note.
* After extraction most markdown tokens will be removed and links will be sanitized aswell and wrapped into bold tags for clearner display.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the body of a given card or null if none was found.
*/
export function getBodyFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
settings: { metadataKeyEventBodyOverride },
} = context;
const overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;
if (!rawFileText.length || overrideBody) return overrideBody;
const rawTextArray = rawFileText.split("\n");
rawTextArray.shift();
const processedArray = rawTextArray.slice(rawTextArray.indexOf("---") + 1);
const finalString = processedArray.join("\n").trim();
return finalString;
}
/**
* Extract the first image from the raw markdown in a note.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the URL of the image to be displayed in a card or null if none where found.
*/
export function getImageUrlFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
file: currentFile,
app,
settings: { metadataKeyEventPictureOverride },
} = context;
const {
vault,
metadataCache: { getFirstLinkpathDest },
} = app;
const override = metadata?.[metadataKeyEventPictureOverride];
if (override) return override;
const internalLinkMatch = rawFileText.match(/!\[\[(?<src>.*)\]\]/);
const matchs =
internalLinkMatch || rawFileText.match(/!\[.*\]\((?<src>.*)\)/);
if (!matchs || !matchs.groups || !matchs.groups.src) return null;
if (internalLinkMatch) {
// https://github.com/obsidianmd/obsidian-releases/pull/1882#issuecomment-1512952295
const file = getFirstLinkpathDest.bind(app.metadataCache)(
matchs.groups.src,
currentFile.path
) satisfies TFile | null;
if (file instanceof TFile) return vault.getResourcePath(file);
// Thanks https://github.com/joethei
return null;
} else return encodeURI(matchs.groups.src);
}
/**
* Given a metadata key it'll try to parse the associated data as an `AbstractDate` and return it
*
* @param param0 - Timeline generic context.
* @param param0.cachedMetadata - The cached metadata from a note.
* @param param0.settings - the plugin's settings.
* @param key - The target lookup key in the notes metadata object.
* @returns the abstract date representation or undefined.
*/
export function getAbstractDateFromMetadata(
{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,
key: string
): AbstractDate | undefined {
const groupsToCheck = | settings.dateParserGroupPriority.split(","); |
const numberValue = getMetadataKey(cachedMetadata, key, "number");
if (isDefined(numberValue)) {
const additionalContentForNumberOnlydate = [
...Array(Math.max(0, groupsToCheck.length - 1)),
].map(() => 0);
return [numberValue, ...additionalContentForNumberOnlydate];
}
const stringValue = getMetadataKey(cachedMetadata, key, "string");
if (!stringValue) return undefined;
return parseAbstractDate(
groupsToCheck,
stringValue,
settings.dateParserRegex
);
}
| src/cardDataExtraction.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param cachedMetadata - cachedMetadata - Obsidians cachedMetadata object.\n * @param key - the sought after key in the obsidian metadata object.\n * @param type - The expected type of the key value.\n * @returns The metadata value assigned to the given key or null if unvalidated or missing.\n */\nexport function getMetadataKey<T extends \"string\" | \"number\" | \"boolean\">(\n\tcachedMetadata: MarkdownCodeBlockTimelineProcessingContext[\"cachedMetadata\"],\n\tkey: string,\n\ttype: T\n):",
"score": 38.814441120312
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": " * @param key - The settings key.\n * @param value - The value associated to this value.\n * @returns Undefined if unvalid or the actual expected value.\n */\nfunction formatValueFromKey(\n\tkey: string,\n\tvalue: string\n): AutoTimelineSettings[OverridableSettingKey] | undefined {\n\tif (!isOverridableSettingsKey(key)) return undefined;\n\tif (isDefinedAsString(SETTINGS_DEFAULT[key])) return value;",
"score": 32.76760820806713
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\t| (T extends \"string\" ? string : T extends \"number\" ? number : boolean)\n\t| undefined {\n\t// Bail if no formatter object or if the key is missing\n\tif (!cachedMetadata.frontmatter) return undefined;\n\treturn typeof cachedMetadata.frontmatter[key] === type\n\t\t? cachedMetadata.frontmatter[key]\n\t\t: undefined;\n}\n/**\n * Typeguard to check if a value is indeed defined.",
"score": 28.307505984784928
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": "\t);\n}\n/**\n * Get the text displayed in the card where the date should be.\n *\n * @param param0 - The context for a single card.\n * @param param0.startDate - the start date of an event.\n * @param param0.endDate - the end date of an event.\n * @param settings - The settings of the plugin.\n * @returns a formated string representation of the dates included in the card content based off the settings.",
"score": 26.34870281069942
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": " *\n * @param param0 - The context built for this timeline.\n * @param param0.elements - The HTMLElements exposed for this context.\n * @param param0.elements.cardListRootElement - The right side of the timeline, this is where the carads are spawned.\n * @param param0.file - The target note file.\n * @param param0.settings - The plugin's settings.\n * @param cardContent - The content of a single timeline card.\n */\nexport function createCardFromBuiltContext(\n\t{",
"score": 24.431141274287643
}
] | typescript | settings.dateParserGroupPriority.split(","); |
import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from "@prisma/client";
import { prisma } from "../../../prisma/client";
export class GetPedidoPorNumeroUseCase {
async getPedidoPorNumero(numero: string): Promise<any | null> {
const pedido = await prisma.pedido.findFirst({
where: {
numero
},
include: {
cliente: {
select: {
nome_completo: true,
cpf: true,
telefone: true,
email: true,
endereco: true
}
}, produto: {
select: {
nome_produto: true,
referencia: true,
descricao: true,
quantidade: true,
valor: true,
}
},
pagamento: {
select: {
tipo_pagamento: true,
parcela: true,
id_transacao: true
}
},
pedido_status: {
select: {
status_pedido: true,
status_erro: true
}
}
}
});
if (!pedido) {
return null;
}
const produtosFormatados: { nome: string; referencia: string; descricao: string; quantidade: number; valor_produto: number; valor_total_produto: number; }[] = [];
pedido.produto | .forEach((produto) => { |
const produtoFormatado = {
nome: produto.nome_produto,
referencia: produto.referencia,
descricao: produto.descricao,
quantidade: produto.quantidade,
valor_produto: produto.valor,
valor_total_produto: produto.valor * produto.quantidade
};
produtosFormatados.push(produtoFormatado);
});
const moment = require('moment');
const pedidoFormatado = {
cpf: pedido.cliente.cpf,
nome: pedido.cliente.nome_completo,
contato: pedido.cliente.telefone,
email: pedido.cliente.email,
endereco: pedido.cliente.endereco,
numeroDoPedido: pedido.numero,
produtos: produtosFormatados,
tipo_pagamento: pedido.pagamento.tipo_pagamento,
parcelas: pedido.pagamento.parcela,
id_transacao: pedido.pagamento.id_transacao,
dataDaCompra: moment(pedido.data_pedido_realizado).format('DD/MM/YYYY'),
status_pedido: pedido.pedido_status.status_pedido,
status_erro: pedido.pedido_status.status_erro
};
return pedidoFormatado;
}
} | src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts | Iguu42-node-project-FC-0cd6618 | [
{
"filename": "src/errors/AppError.ts",
"retrieved_chunk": "export class AppError {\n public readonly message: string;\n public readonly statusCode: number;\n constructor(message: string, statusCode = 400) {\n this.message = message;\n this.statusCode = statusCode;\n }\n}",
"score": 19.101173042028712
},
{
"filename": "src/modules/pedidos/comentarios/ResponderComentarioUseCase.ts",
"retrieved_chunk": "import { prisma } from \"../../../prisma/client\";\nexport class ResponderComentarioUseCase {\n public responderComentario = async (id_comentario: number, id_pedido: string, resposta: string) => {\n const novaResposta = await prisma.comentario.create({\n data: {\n id_pedido: id_pedido,\n conteudo: resposta,\n comentario_pai_id: id_comentario\n }\n });",
"score": 17.631973075799912
},
{
"filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts",
"retrieved_chunk": " });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {\n return total + (produto.valor * produto.quantidade);\n }, 0);\n return {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,\n numeroDoPedido: pedido.numero,",
"score": 12.966916765787147
},
{
"filename": "src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts",
"retrieved_chunk": "import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from \"@prisma/client\";\nimport { prisma } from \"../../../prisma/client\";\nexport class GetPedidoPorCpfUseCase {\n async getPedidoPorCpf(numero: string): Promise<any | null> {\n if (numero.length === 11) {\n const clienteCpf = await prisma.cliente.findFirst({\n where: {\n cpf: numero\n }\n });",
"score": 12.802285131343755
},
{
"filename": "src/modules/validarLogin/GetLoginUseCase.ts",
"retrieved_chunk": "import { prisma } from \"../../prisma/client\";\nimport { login } from \"@prisma/client\";\nexport class GetLoginUseCase {\n async execute(email: string, senha: string): Promise<any> {\n const user = await prisma.login.findFirst({\n where: {\n email,\n },\n });\n if (!user) {",
"score": 10.849907533500092
}
] | typescript | .forEach((produto) => { |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await | getDataFromNoteMetadata(context, tagsToFind); |
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": "import type { App } from \"obsidian\";\nimport type {\n\tAutoTimelineSettings,\n\tMarkdownCodeBlockTimelineProcessingContext,\n} from \"~/types\";\n/**\n * A preliminary helper to fetch all the needed context to handle the timeline creation.\n *\n * @param app - The app context provided by obsidian.\n * @param element - The root element of this timeline.",
"score": 16.121672954120886
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 13.55105752641202
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 13.327734148969103
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,",
"score": 12.129409272499736
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 12.04223231704816
}
] | typescript | getDataFromNoteMetadata(context, tagsToFind); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
| const score = compareAbstractDates(a, b); |
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0",
"score": 30.681485891989798
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\trelatedCardData: {\n\t\t\t\t\t...relatedCardData,\n\t\t\t\t\tcardData: {\n\t\t\t\t\t\t...relatedCardData.cardData,\n\t\t\t\t\t\tendDate,\n\t\t\t\t\t\tstartDate,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\ttargetPosition,\n\t\t\t\tcardRelativeTopPosition,",
"score": 23.01266242488445
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||",
"score": 21.919830672134488
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tindex,\n\t\t\t} as const);\n\t\t\treturn accumulator;\n\t\t},\n\t\t[] as {\n\t\t\treadonly relatedCardData: CompleteCardContext & {\n\t\t\t\tcardData: CompleteCardContext[\"cardData\"] & {\n\t\t\t\t\tstartDate: AbstractDate;\n\t\t\t\t\tendDate: AbstractDate | true;\n\t\t\t\t};",
"score": 20.742916821386956
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": " */\nexport function getDateText(\n\t{ startDate, endDate }: Pick<CardContent, \"startDate\" | \"endDate\">,\n\tsettings: AutoTimelineSettings\n): string {\n\tif (!isDefined(startDate)) return \"Start date missing\";\n\tconst formatedStart = formatAbstractDate(startDate, settings);\n\tif (!isDefined(endDate)) return formatedStart;\n\treturn `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;\n}",
"score": 20.556854867370337
}
] | typescript | const score = compareAbstractDates(a, b); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
| if (isDefined(baseData)) events.push(baseData); |
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 17.962100027926365
},
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": "import type { App } from \"obsidian\";\nimport type {\n\tAutoTimelineSettings,\n\tMarkdownCodeBlockTimelineProcessingContext,\n} from \"~/types\";\n/**\n * A preliminary helper to fetch all the needed context to handle the timeline creation.\n *\n * @param app - The app context provided by obsidian.\n * @param element - The root element of this timeline.",
"score": 16.121672954120886
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 13.722830515471829
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 12.516287987759627
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,",
"score": 12.446167566333818
}
] | typescript | if (isDefined(baseData)) events.push(baseData); |
import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from "@prisma/client";
import { prisma } from "../../../prisma/client";
export class GetPedidoPorCpfUseCase {
async getPedidoPorCpf(numero: string): Promise<any | null> {
if (numero.length === 11) {
const clienteCpf = await prisma.cliente.findFirst({
where: {
cpf: numero
}
});
if (clienteCpf) {
const pedido = await prisma.pedido.findMany({
where: {
id_cliente: clienteCpf.id_cliente
},
include: {
cliente: {
select: {
nome_completo: true,
cpf: true
}
},
pedido_status: {
select: {
status_pedido: true,
status_erro: true
}
},
nota_fiscal: {
select: {
numero_nota: true
}
},
pagamento: {
select: {
tipo_pagamento: true,
parcela: true
}
},
produto: {
select: {
nome_produto: true,
quantidade: true
}
}
}
});
if (!pedido) {
return null;
}
| const pedidosFormatados = pedido.map((pedido) => ({ |
numero: pedido.numero,
status_pedido: pedido.pedido_status.status_pedido,
status_erro: pedido.pedido_status.status_erro,
numero_nota_fiscal: pedido.nota_fiscal.numero_nota,
data_pedido_realizado: pedido.data_pedido_realizado,
nome_cliente: pedido.cliente.nome_completo,
cpf_cliente: pedido.cliente.cpf,
tipo_pagamento: pedido.pagamento.tipo_pagamento,
}));
return pedidosFormatados;
}
}
}
}
| src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts | Iguu42-node-project-FC-0cd6618 | [
{
"filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts",
"retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {",
"score": 15.876385935179673
},
{
"filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts",
"retrieved_chunk": " })\n if (!pedidos) {\n return null\n }\n const pedidosFormatados = pedidos.map(pedido => ({\n status_pedido: pedido.pedido_status.status_pedido,\n status_erro: pedido.pedido_status.status_erro,\n pedido: pedido.cliente.cpf,\n numero_nota_fiscal: pedido.nota_fiscal.numero_nota,\n data_pedido_realizado: pedido.data_pedido_realizado,",
"score": 13.646558800034954
},
{
"filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts",
"retrieved_chunk": " }\n },\n produto: {\n select: {\n nome_produto: true,\n quantidade: true,\n valor: true\n }\n }\n }",
"score": 11.97806115221875
},
{
"filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts",
"retrieved_chunk": " nome_cliente: pedido.cliente.nome_completo,\n tipo_pagamento: pedido.pagamento.tipo_pagamento,\n // valor_e_parcela: `${pedido.pagamento.parcela}x - R$${pedido.produto.valor}`,\n // nome_produto: pedido.produto.nome_produto,\n // quantidade_produto: pedido.produto.quantidade\n }))\n return pedidosFormatados\n }\n}",
"score": 11.38846461311065
},
{
"filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts",
"retrieved_chunk": " });\n if (!pedido) {\n return null;\n }\n const produtosFormatados: { nome: string; referencia: string; descricao: string; quantidade: number; valor_produto: number; valor_total_produto: number; }[] = [];\n pedido.produto.forEach((produto) => {\n const produtoFormatado = {\n nome: produto.nome_produto,\n referencia: produto.referencia,\n descricao: produto.descricao,",
"score": 11.239635013664042
}
] | typescript | const pedidosFormatados = pedido.map((pedido) => ({ |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
| events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
); |
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0",
"score": 17.32389109418687
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||",
"score": 12.82746679764554
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\t? compareAbstractDates(startDate, date) <= 0\n\t\t\t\t: false\n\t);\n\tif (firstLastUnderIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members\"\n\t\t);\n\tconst lastUnderIndex = collection.findIndex(\n\t\t({ cardData: { startDate } }, index) => {\n\t\t\treturn (",
"score": 12.237401811710662
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 11.436051601805769
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 11.171885031271474
}
] | typescript | events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
| { cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } } |
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 30.653120438469557
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0",
"score": 29.250020444615945
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\trelatedCardData: {\n\t\t\t\t\t...relatedCardData,\n\t\t\t\t\tcardData: {\n\t\t\t\t\t\t...relatedCardData.cardData,\n\t\t\t\t\t\tendDate,\n\t\t\t\t\t\tstartDate,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\ttargetPosition,\n\t\t\t\tcardRelativeTopPosition,",
"score": 23.01266242488445
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||",
"score": 21.91983067213449
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tindex,\n\t\t\t} as const);\n\t\t\treturn accumulator;\n\t\t},\n\t\t[] as {\n\t\t\treadonly relatedCardData: CompleteCardContext & {\n\t\t\t\tcardData: CompleteCardContext[\"cardData\"] & {\n\t\t\t\t\tstartDate: AbstractDate;\n\t\t\t\t\tendDate: AbstractDate | true;\n\t\t\t\t};",
"score": 20.742916821386956
}
] | typescript | { cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } } |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const | runtimeTime = measureTime("Run time"); |
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": "import type { App } from \"obsidian\";\nimport type {\n\tAutoTimelineSettings,\n\tMarkdownCodeBlockTimelineProcessingContext,\n} from \"~/types\";\n/**\n * A preliminary helper to fetch all the needed context to handle the timeline creation.\n *\n * @param app - The app context provided by obsidian.\n * @param element - The root element of this timeline.",
"score": 18.67245627262456
},
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": " * @param timelineFile - The file path of the timeline.\n * @param settings - The plugin's settings.\n * @returns the nessessary context to build a timeline.\n */\nexport function setupTimelineCreation(\n\tapp: App,\n\telement: HTMLElement,\n\ttimelineFile: string,\n\tsettings: AutoTimelineSettings\n) {",
"score": 16.35108591469244
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param el - The root element.\n * @param element - The desired HTML tag.\n * @param classes - A single or a collection of tags.\n * @param content - The content to inject inside the created element.\n * @returns The created element.\n */\nexport function createElementShort(\n\tel: HTMLElement,\n\telement: keyof HTMLElementTagNameMap,\n\tclasses?: string[] | string,",
"score": 15.314620237641915
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 12.825873724864493
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": " *\n * @param date - The target endDate to position on the timeline.\n * @param collection - The collection of cards part of the same timeline.\n * @param timelineLength - The length in pixel of the timeline.\n * @param rootElement - The root HTMLElement of the cardList.\n * @param indexOffset - Since the date is already sorted by date we can save a little time by skipping all the elements before.\n * @returns The expected position relative to the top of the timeline container for this date range.\n */\nexport function findEndPositionForDate(\n\tdate: AbstractDate,",
"score": 12.634617935859568
}
] | typescript | runtimeTime = measureTime("Run time"); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await | getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined); |
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 52.492365208458075
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tconst fileTitle =\n\t\tc.frontmatter?.[settings.metadataKeyEventTitleOverride] ||\n\t\tfile.basename;\n\trawFileContent = rawFileContent || (await file.vault.cachedRead(file));\n\treturn {\n\t\ttitle: fileTitle as string,\n\t\tbody: getBodyFromContextOrDocument(rawFileContent, context),\n\t\timageURL: getImageUrlFromContextOrDocument(rawFileContent, context),\n\t\tstartDate: getAbstractDateFromMetadata(\n\t\t\tcontext,",
"score": 46.9678206642742
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,",
"score": 32.24859574921952
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 30.00466064455207
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tcontext,\n\t} as const;\n}\n/**\n * Provides additional context for the creation cards in the DOM but reads it from the body\n *\n * @param body - The extracted body for a single event card.\n * @param context - Timeline generic context.\n * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.",
"score": 26.30668432785317
}
] | typescript | getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
| this.addSettingTab(new TimelineSettingTab(this.app, this)); |
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\t? compareAbstractDates(startDate, date) <= 0\n\t\t\t\t: false\n\t);\n\tif (firstLastUnderIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members\"\n\t\t);\n\tconst lastUnderIndex = collection.findIndex(\n\t\t({ cardData: { startDate } }, index) => {\n\t\t\treturn (",
"score": 34.16007905891004
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\t\t};\n\t\t\t\t\t\tvalue.value = this.plugin.settings;\n\t\t\t\t\t\tawait this.plugin.saveSettings();\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t\tmethods: {},\n\t\t});\n\t\tthis.vueApp.use(i18n).mount(this.containerEl);\n\t}",
"score": 31.869477142503566
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\tcomponents: { VApp },\n\t\t\ttemplate: \"<VApp :value='value' @update:value='save' />\",\n\t\t\tsetup: () => {\n\t\t\t\tconst value = ref(this.plugin.settings);\n\t\t\t\treturn {\n\t\t\t\t\tvalue,\n\t\t\t\t\tsave: async (payload: Partial<AutoTimelineSettings>) => {\n\t\t\t\t\t\tthis.plugin.settings = {\n\t\t\t\t\t\t\t...this.plugin.settings,\n\t\t\t\t\t\t\t...payload,",
"score": 29.373907039626296
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tconstructor(app: ObsidianApp, plugin: AprilsAutomaticTimelinesPlugin) {\n\t\tsuper(app, plugin);\n\t\tthis.plugin = plugin;\n\t\tthis.vueApp = null;\n\t}\n\tdisplay(): void {\n\t\tthis.containerEl.empty();\n\t\t// TODO Read locale off obsidian.\n\t\tconst i18n = createVueI18nConfig();\n\t\tthis.vueApp = createApp({",
"score": 29.326619452491432
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tarr: T,\n\tpredicate: (arg: T[number]) => boolean\n): number {\n\tconst length = arr ? arr.length : 0;\n\tif (!length) return -1;\n\tlet index = length - 1;\n\twhile (index--) if (predicate(arr[index])) return index;\n\treturn -1;\n}\n/**",
"score": 27.64131019369504
}
] | typescript | this.addSettingTab(new TimelineSettingTab(this.app, this)); |
import { SETTINGS_DEFAULT } from "~/settings";
import { FnGetRangeData } from "./rangeData";
import { FnExtractCardData, getDataFromNoteMetadata } from "~/cardData";
import type { App, CachedMetadata, TFile } from "obsidian";
import type { Merge } from "ts-essentials";
/**
* @author https://stackoverflow.com/a/69756175
*/
export type PickByType<T, Value> = {
[P in keyof T as T[P] extends Value | undefined ? P : never]: T[P];
};
export type AutoTimelineSettings = typeof SETTINGS_DEFAULT;
/**
* The main bundle of data needed to build a timeline.
*/
export interface MarkdownCodeBlockTimelineProcessingContext {
/**
* Obsidian application context.
*/
app: App;
/**
* The plugins settings
*/
settings: AutoTimelineSettings;
/**
* The formatted metadata of a single note.
*/
cachedMetadata: CachedMetadata;
/**
* The file data of a single note.
*/
file: TFile;
/**
* The filepath of a single timeline.
*/
timelineFile: string;
/**
* Shorthand access to HTMLElements for the range timelines and the card list.
*/
elements: {
timelineRootElement: HTMLElement;
cardListRootElement: HTMLElement;
};
}
/**
* The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.
*/
export type CompleteCardContext = Exclude<
Awaited<ReturnType<typeof getDataFromNoteMetadata>>,
undefined
>;
/**
* The context extracted from a single note to create a single card in the timeline.
*/
export type CardContent = Awaited<ReturnType<FnExtractCardData>>;
/**
* The needed data to compute a range in a single timeline.
*/
| export type Range = ReturnType<FnGetRangeData>[number]; |
/**
* An abstract representation of a fantasy date.
* Given the fickle nature of story telling and how people will literally almost never stick to standard date formats
* We'll organise the dates in segments, let's take for example our human callendar
* The date will commonly be segmented in 3 parts year, month and day the abstract representation will equate to
* `[year, month, day]`
* Now if someone wants to make a more complex date system like `[cycle, moon, phase, day]` we can treat them the same when sorting and performing computing tasks on those dates.
* The only major limitation to this system is that all the dates must respect the same system.
*/
export type AbstractDate = number[];
/**
* Before formatting an abstract date, the end user can configure it's output display
* This DateToken type helps to determine what's the nature of a given token
* E.g. should it be displayed as a number or as a string ?
*/
export enum DateTokenType {
number = "NUMBER",
string = "STRING",
}
export const availableDateTokenTypeArray = Object.values(DateTokenType);
export enum Condition {
Greater = "GREATER",
Less = "LESS",
Equal = "EQUAL",
NotEqual = "NOTEQUAL",
GreaterOrEqual = "GREATEROREQUAL",
LessOrEqual = "LESSOREQUAL",
}
export const availableConditionArray = Object.values(Condition);
export type Evaluation<T extends number = number> = {
condition: Condition;
value: T;
};
export type AdditionalDateFormatting<T extends number = number> = {
evaluations: Evaluation<T>[];
/**
* Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.
*/
conditionsAreExclusive: boolean;
/**
* Use `{value}` to include the pre-formated output of the numerical value held.
*/
format: string;
};
/**
* The data used to compute the output of an abstract date based on it's type
*/
type CommonValues<T extends DateTokenType> = {
name: string;
type: T;
formatting: AdditionalDateFormatting[];
};
export type DateTokenConfiguration<T extends DateTokenType = DateTokenType> =
T extends DateTokenType.number
? NumberSpecific
: T extends DateTokenType.string
? StringSpecific
: StringSpecific | NumberSpecific;
/**
* Number typed date token.
*/
type NumberSpecific = Merge<
CommonValues<DateTokenType.number>,
{
/**
* The minimum ammount of digits when displaying the date
*/
minLeght: number;
displayWhenZero: boolean;
hideSign: boolean;
}
>;
/**
* String typed date token.
*/
type StringSpecific = Merge<
CommonValues<DateTokenType.string>,
{
/**
* The dictionary reference for the token
*/
dictionary: string[];
}
>;
| src/types.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": " * Will compute all the data needed to build ranges in the timeline.\n *\n * @param collection - The complete collection of relevant data gathered from notes.\n * @returns the needed data to build ranges in the timeline.\n */\nexport function getAllRangeData(collection: CompleteCardContext[]) {\n\tif (!collection.length) return [];\n\treturn collection.reduce(\n\t\t(accumulator, relatedCardData, index) => {\n\t\t\tconst {",
"score": 28.193318061802234
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tcontext,\n\t} as const;\n}\n/**\n * Provides additional context for the creation cards in the DOM but reads it from the body\n *\n * @param body - The extracted body for a single event card.\n * @param context - Timeline generic context.\n * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.",
"score": 27.949833714566374
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t};\n\t\t\treadonly index: number;\n\t\t\treadonly targetPosition: number;\n\t\t\treadonly cardRelativeTopPosition: number;\n\t\t}[]\n\t);\n}\nexport type FnGetRangeData = typeof getAllRangeData;\n/**\n * Finds the end position in pixel relative to the top of the timeline root element for the give endDate of a range.",
"score": 24.590694609402878
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t(source, element, context) => {\n\t\t\t\tthis.run(source, element, context);\n\t\t\t}\n\t\t);\n\t}\n\tonunload() {}\n\t/**\n\t * Main runtime function to process a single timeline.\n\t *\n\t * @param source - The content found in the markdown block.",
"score": 24.55424141805444
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 23.818126859386282
}
] | typescript | export type Range = ReturnType<FnGetRangeData>[number]; |
import { SETTINGS_DEFAULT } from "~/settings";
import { AutoTimelineSettings } from "./types";
import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils";
/**
* Fetches the tags to find and timeline specific settings override.
*
* @param source - The markdown code block source, a.k.a. the content inside the code block.
* @returns Partial settings to override the global ones.
*/
export function parseMarkdownBlockSource(source: string): {
readonly tagsToFind: string[];
readonly settingsOverride: Partial<AutoTimelineSettings>;
} {
const sourceEntries = source.split("\n");
if (!source.length)
return { tagsToFind: [] as string[], settingsOverride: {} } as const;
const tagsToFind = sourceEntries[0]
.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)
.map((e) => e.trim());
sourceEntries.shift();
return {
tagsToFind,
settingsOverride: sourceEntries.reduce((accumulator, element) => {
return {
...accumulator,
...parseSingleLine(element),
};
}, {} as Partial<AutoTimelineSettings>),
} as const;
}
type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];
const acceptedSettingsOverride = [
"dateDisplayFormat",
"applyAdditonalConditionFormatting",
] as const;
/**
* Checks if a given string is part of the settings keys that can be overriden.
*
* @param value - A given settings key.
* @returns the typeguard boolean `true` if the key is indeed overridable.
*/
function isOverridableSettingsKey(
value: string
): value is OverridableSettingKey {
// @ts-expect-error
return acceptedSettingsOverride.includes(value);
}
/**
* Will apply the needed formatting to a setting value based of it's key.
*
* @param key - The settings key.
* @param value - The value associated to this value.
* @returns Undefined if unvalid or the actual expected value.
*/
function formatValueFromKey(
key: string,
value: string
): AutoTimelineSettings[OverridableSettingKey] | undefined {
if (!isOverridableSettingsKey(key)) return undefined;
if | (isDefinedAsString(SETTINGS_DEFAULT[key])) return value; |
if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) {
const validBooleanStrings = ["true", "false"];
if (!validBooleanStrings.includes(value.toLocaleLowerCase()))
throw new Error(`${value} is supposed to be a boolean`);
return value.toLocaleLowerCase() === "true" ? true : false;
}
return undefined;
}
/**
* Parse a single line of the timeline markdown block content.
*
* @param line - The line to parse.
* @returns A potencialy partial settings object.
*/
function parseSingleLine(line: string): Partial<AutoTimelineSettings> {
const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i;
const matches = line.match(reg);
if (
!matches ||
!matches.groups ||
!isDefinedAsString(matches.groups.key) ||
!isDefined(matches.groups.value)
)
return {};
const key = matches.groups.key.trim();
const value = formatValueFromKey(key, matches.groups.value.trim());
if (!isDefined(value)) return {};
return { [key]: value };
}
| src/markdownBlockData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param cachedMetadata - cachedMetadata - Obsidians cachedMetadata object.\n * @param key - the sought after key in the obsidian metadata object.\n * @param type - The expected type of the key value.\n * @returns The metadata value assigned to the given key or null if unvalidated or missing.\n */\nexport function getMetadataKey<T extends \"string\" | \"number\" | \"boolean\">(\n\tcachedMetadata: MarkdownCodeBlockTimelineProcessingContext[\"cachedMetadata\"],\n\tkey: string,\n\ttype: T\n):",
"score": 42.82277497500939
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "}\n/**\n * Typeguard to check if a value is an object of unknowed key values.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an object, `false` if not.\n */\nexport function isDefinedAsObject(\n\tvalue: unknown\n): value is { [key: string]: unknown } {",
"score": 40.87296132459455
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\t| (T extends \"string\" ? string : T extends \"number\" ? number : boolean)\n\t| undefined {\n\t// Bail if no formatter object or if the key is missing\n\tif (!cachedMetadata.frontmatter) return undefined;\n\treturn typeof cachedMetadata.frontmatter[key] === type\n\t\t? cachedMetadata.frontmatter[key]\n\t\t: undefined;\n}\n/**\n * Typeguard to check if a value is indeed defined.",
"score": 38.24155946435762
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " *\n * @param value - Date token configuration.\n * @returns typeguard.\n */\nexport function dateTokenConfigurationIsTypeString(\n\tvalue: DateTokenConfiguration\n): value is DateTokenConfiguration<DateTokenType.string> {\n\treturn value.type === DateTokenType.string;\n}\n/**",
"score": 31.26260182661991
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\tcomponents: { VApp },\n\t\t\ttemplate: \"<VApp :value='value' @update:value='save' />\",\n\t\t\tsetup: () => {\n\t\t\t\tconst value = ref(this.plugin.settings);\n\t\t\t\treturn {\n\t\t\t\t\tvalue,\n\t\t\t\t\tsave: async (payload: Partial<AutoTimelineSettings>) => {\n\t\t\t\t\t\tthis.plugin.settings = {\n\t\t\t\t\t\t\t...this.plugin.settings,\n\t\t\t\t\t\t\t...payload,",
"score": 30.19884496371302
}
] | typescript | (isDefinedAsString(SETTINGS_DEFAULT[key])) return value; |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) {
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: string | Did,
asArray = true
): ReturnBuilderWithController<this> {
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addService(service: ServiceOptions): ReturnBuilderWithService<this> {
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public | findServiceByType(type: string): Service { |
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/schemas/didSchema.ts",
"retrieved_chunk": " return new Did(did)\n } else if (did instanceof Did) {\n return did\n } else {\n throw new DidError(`id must be of type 'string' or an instance of 'Did'`)\n }\n })\nexport const stringOrDidUrl = z\n .union([\n didUrlSchemaWithouttransformation,",
"score": 12.872165009286137
},
{
"filename": "src/verificationMethodTypes.ts",
"retrieved_chunk": "/**\n * These are values to be used for the type in a verification method object.\n *\n * @see {@link https://www.w3.org/TR/did-spec-registries/#verification-method-types}\n *\n * @note Do not include private or extraneous information in verification methods. The class of private information related to JWKs is defined here. Please review the DID Core specification for additional details on this topic.\n */\nexport enum VerificationMethodTypes {\n /**\n * @see {@link https://w3c-ccg.github.io/lds-jws2020/ | Normative definition}",
"score": 12.655265382087045
},
{
"filename": "src/schemas/didSchema.ts",
"retrieved_chunk": " z.custom<Did>((did) => did instanceof Did),\n ])\n .transform((did: string | Did): Did => {\n if (typeof did === 'string') {\n return new Did(did)\n } else if (did instanceof Did) {\n return did\n } else {\n throw new DidError(`id must be of type 'string' or an instance of 'Did'`)\n }",
"score": 11.918621147240248
},
{
"filename": "src/verificationMethod.ts",
"retrieved_chunk": " this.controller = controller\n this.type = type\n this.publicKeyJwk = publicKeyJwk\n this.publicKeyMultibase = publicKeyMultibase\n }\n /**\n * Checks whether the verification method type is registered inside the @{link https://www.w3.org/TR/did-spec-registries/#verification-method-types | verification method types}\n *\n */\n public isTypeInDidSpecRegistry(",
"score": 11.818031136980922
},
{
"filename": "src/schemas/verificationMethodSchema.ts",
"retrieved_chunk": " .transform((verificationMethod) => {\n if (verificationMethod instanceof Did) {\n return verificationMethod\n }\n return new VerificationMethod(verificationMethod)\n })\nexport const uniqueStringOrVerificationMethodsSchema = (name: string) =>\n z.array(stringOrVerificationMethod).refine((verificationMethods) => {\n const idSet = new Set()\n for (const obj of verificationMethods) {",
"score": 10.734390678396712
}
] | typescript | findServiceByType(type: string): Service { |
import { SETTINGS_DEFAULT } from "~/settings";
import { AutoTimelineSettings } from "./types";
import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils";
/**
* Fetches the tags to find and timeline specific settings override.
*
* @param source - The markdown code block source, a.k.a. the content inside the code block.
* @returns Partial settings to override the global ones.
*/
export function parseMarkdownBlockSource(source: string): {
readonly tagsToFind: string[];
readonly settingsOverride: Partial<AutoTimelineSettings>;
} {
const sourceEntries = source.split("\n");
if (!source.length)
return { tagsToFind: [] as string[], settingsOverride: {} } as const;
const tagsToFind = sourceEntries[0]
.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)
.map((e) => e.trim());
sourceEntries.shift();
return {
tagsToFind,
settingsOverride: sourceEntries.reduce((accumulator, element) => {
return {
...accumulator,
...parseSingleLine(element),
};
}, {} as Partial<AutoTimelineSettings>),
} as const;
}
type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];
const acceptedSettingsOverride = [
"dateDisplayFormat",
"applyAdditonalConditionFormatting",
] as const;
/**
* Checks if a given string is part of the settings keys that can be overriden.
*
* @param value - A given settings key.
* @returns the typeguard boolean `true` if the key is indeed overridable.
*/
function isOverridableSettingsKey(
value: string
): value is OverridableSettingKey {
// @ts-expect-error
return acceptedSettingsOverride.includes(value);
}
/**
* Will apply the needed formatting to a setting value based of it's key.
*
* @param key - The settings key.
* @param value - The value associated to this value.
* @returns Undefined if unvalid or the actual expected value.
*/
function formatValueFromKey(
key: string,
value: string
| ): AutoTimelineSettings[OverridableSettingKey] | undefined { |
if (!isOverridableSettingsKey(key)) return undefined;
if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value;
if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) {
const validBooleanStrings = ["true", "false"];
if (!validBooleanStrings.includes(value.toLocaleLowerCase()))
throw new Error(`${value} is supposed to be a boolean`);
return value.toLocaleLowerCase() === "true" ? true : false;
}
return undefined;
}
/**
* Parse a single line of the timeline markdown block content.
*
* @param line - The line to parse.
* @returns A potencialy partial settings object.
*/
function parseSingleLine(line: string): Partial<AutoTimelineSettings> {
const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i;
const matches = line.match(reg);
if (
!matches ||
!matches.groups ||
!isDefinedAsString(matches.groups.key) ||
!isDefined(matches.groups.value)
)
return {};
const key = matches.groups.key.trim();
const value = formatValueFromKey(key, matches.groups.value.trim());
if (!isDefined(value)) return {};
return { [key]: value };
}
| src/markdownBlockData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param cachedMetadata - cachedMetadata - Obsidians cachedMetadata object.\n * @param key - the sought after key in the obsidian metadata object.\n * @param type - The expected type of the key value.\n * @returns The metadata value assigned to the given key or null if unvalidated or missing.\n */\nexport function getMetadataKey<T extends \"string\" | \"number\" | \"boolean\">(\n\tcachedMetadata: MarkdownCodeBlockTimelineProcessingContext[\"cachedMetadata\"],\n\tkey: string,\n\ttype: T\n):",
"score": 50.64072628477946
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "}\n/**\n * Typeguard to check if a value is an object of unknowed key values.\n *\n * @param value unknowed value.\n * @returns `true` if the element is defined as an object, `false` if not.\n */\nexport function isDefinedAsObject(\n\tvalue: unknown\n): value is { [key: string]: unknown } {",
"score": 45.72610569490336
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\t| (T extends \"string\" ? string : T extends \"number\" ? number : boolean)\n\t| undefined {\n\t// Bail if no formatter object or if the key is missing\n\tif (!cachedMetadata.frontmatter) return undefined;\n\treturn typeof cachedMetadata.frontmatter[key] === type\n\t\t? cachedMetadata.frontmatter[key]\n\t\t: undefined;\n}\n/**\n * Typeguard to check if a value is indeed defined.",
"score": 37.703697417343925
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string",
"score": 34.17171271952632
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\tcomponents: { VApp },\n\t\t\ttemplate: \"<VApp :value='value' @update:value='save' />\",\n\t\t\tsetup: () => {\n\t\t\t\tconst value = ref(this.plugin.settings);\n\t\t\t\treturn {\n\t\t\t\t\tvalue,\n\t\t\t\t\tsave: async (payload: Partial<AutoTimelineSettings>) => {\n\t\t\t\t\t\tthis.plugin.settings = {\n\t\t\t\t\t\t\t...this.plugin.settings,\n\t\t\t\t\t\t\t...payload,",
"score": 31.219113032024424
}
] | typescript | ): AutoTimelineSettings[OverridableSettingKey] | undefined { |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) {
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: | string | Did,
asArray = true
): ReturnBuilderWithController<this> { |
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addService(service: ServiceOptions): ReturnBuilderWithService<this> {
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public findServiceByType(type: string): Service {
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/did.ts",
"retrieved_chunk": " }\n public static validateDidUrl(did: z.input<typeof stringOrDidUrl>): boolean {\n return stringOrDidUrl.safeParse(did).success\n }\n public validate(): boolean {\n if (this.isDidUrl()) {\n return Did.validateDidUrl(this.toUrl())\n } else {\n return Did.validateDid(this.did)\n }",
"score": 15.527790646395323
},
{
"filename": "src/did.ts",
"retrieved_chunk": " return this\n }\n public addPath(path: string): this {\n if (this.path) {\n this.path = this.path + this.addPrefixIfNotSupplied(path, PREFIX_PATH)\n } else {\n return this.withPath(path)\n }\n return this\n }",
"score": 15.322872867938168
},
{
"filename": "src/did.ts",
"retrieved_chunk": " this.query = { ...this.query, ...query }\n } else {\n this.withQuery(query)\n }\n return this\n }\n public removeQuery(): this {\n this.query = undefined\n return this\n }",
"score": 15.051428753638731
},
{
"filename": "src/did.ts",
"retrieved_chunk": " }\n return `${p}${s}`\n }\n public addParameterKey(key: string | Array<string>): this {\n if (typeof key === 'string') {\n this.parameterKeys.push(key)\n } else if (Array.isArray(key)) {\n this.parameterKeys.push(...key)\n }\n return this",
"score": 13.864588547507394
},
{
"filename": "src/did.ts",
"retrieved_chunk": " public removePath(): this {\n this.path = undefined\n return this\n }\n public withQuery(query: Record<string, string>): this {\n this.query = query\n return this\n }\n public addQuery(query: Record<string, string>): this {\n if (this.query) {",
"score": 12.989698872240245
}
] | typescript | string | Did,
asArray = true
): ReturnBuilderWithController<this> { |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
| index < this.settings.dateTokenConfiguration.length; |
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\t\t};\n\t\t\t\t\t\tvalue.value = this.plugin.settings;\n\t\t\t\t\t\tawait this.plugin.saveSettings();\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t\tmethods: {},\n\t\t});\n\t\tthis.vueApp.use(i18n).mount(this.containerEl);\n\t}",
"score": 21.327200858091715
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\tcomponents: { VApp },\n\t\t\ttemplate: \"<VApp :value='value' @update:value='save' />\",\n\t\t\tsetup: () => {\n\t\t\t\tconst value = ref(this.plugin.settings);\n\t\t\t\treturn {\n\t\t\t\t\tvalue,\n\t\t\t\t\tsave: async (payload: Partial<AutoTimelineSettings>) => {\n\t\t\t\t\t\tthis.plugin.settings = {\n\t\t\t\t\t\t\t...this.plugin.settings,\n\t\t\t\t\t\t\t...payload,",
"score": 19.51690424335937
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tarr: T,\n\tpredicate: (arg: T[number]) => boolean\n): number {\n\tconst length = arr ? arr.length : 0;\n\tif (!length) return -1;\n\tlet index = length - 1;\n\twhile (index--) if (predicate(arr[index])) return index;\n\treturn -1;\n}\n/**",
"score": 16.711891946750953
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\t? compareAbstractDates(startDate, date) <= 0\n\t\t\t\t: false\n\t);\n\tif (firstLastUnderIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members\"\n\t\t);\n\tconst lastUnderIndex = collection.findIndex(\n\t\t({ cardData: { startDate } }, index) => {\n\t\t\treturn (",
"score": 15.744617706473893
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tif (!isDefined(a) && !isDefined(b)) return 0;\n\tif (!isDefined(a)) return -1;\n\tif (!isDefined(b)) return 1;\n\tif (a === true && b !== true) return 1;\n\tif (b === true && a !== true) return -1;\n\tif (a === true && b === true) return 0;\n\ta = a as AbstractDate;\n\tb = b as AbstractDate;\n\tfor (let index = 0; index < a.length; index++)\n\t\tif (a[index] !== b[index]) return a[index] > b[index] ? 1 : -1;",
"score": 14.761109123808813
}
] | typescript | index < this.settings.dateTokenConfiguration.length; |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) {
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: string | Did,
asArray = true
): ReturnBuilderWithController<this> {
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addService(service: ServiceOptions): ReturnBuilderWithService<this> {
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public findServiceByType(type: string): Service {
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
| id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean { |
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/verificationMethod.ts",
"retrieved_chunk": " additionalAcceptedTypes: string | Array<string> = []\n ): boolean {\n const additionalAcceptedTypesArray =\n typeof additionalAcceptedTypes === 'string'\n ? [additionalAcceptedTypes]\n : additionalAcceptedTypes\n const allTypes = (\n Object.values(VerificationMethodTypes) as Array<string>\n ).concat(additionalAcceptedTypesArray)\n return allTypes.includes(this.type)",
"score": 20.98553138016349
},
{
"filename": "src/service.ts",
"retrieved_chunk": " */\n public isTypeInDidSpecRegistry(\n additionalAcceptedTypes: string | Array<string> = []\n ): boolean {\n const additionalAcceptedTypesArray =\n typeof additionalAcceptedTypes === 'string'\n ? [additionalAcceptedTypes]\n : additionalAcceptedTypes\n const allTypes = (Object.values(ServiceTypes) as Array<string>).concat(\n additionalAcceptedTypesArray",
"score": 18.813789749133296
},
{
"filename": "src/did.ts",
"retrieved_chunk": " }\n public static validateDidUrl(did: z.input<typeof stringOrDidUrl>): boolean {\n return stringOrDidUrl.safeParse(did).success\n }\n public validate(): boolean {\n if (this.isDidUrl()) {\n return Did.validateDidUrl(this.toUrl())\n } else {\n return Did.validateDid(this.did)\n }",
"score": 13.947806636221136
},
{
"filename": "src/did.ts",
"retrieved_chunk": " }\n return prev\n }, {})\n : undefined\n }\n public isDidUrl(): boolean {\n return Boolean(this.path || this.query || this.fragment)\n }\n public static validateDid(did: z.input<typeof stringOrDid>): boolean {\n return stringOrDid.safeParse(did).success",
"score": 13.624529005998983
},
{
"filename": "src/did.ts",
"retrieved_chunk": " }\n return `${p}${s}`\n }\n public addParameterKey(key: string | Array<string>): this {\n if (typeof key === 'string') {\n this.parameterKeys.push(key)\n } else if (Array.isArray(key)) {\n this.parameterKeys.push(...key)\n }\n return this",
"score": 12.728315462291578
}
] | typescript | id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean { |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
| public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) { |
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: string | Did,
asArray = true
): ReturnBuilderWithController<this> {
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addService(service: ServiceOptions): ReturnBuilderWithService<this> {
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public findServiceByType(type: string): Service {
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/service.ts",
"retrieved_chunk": "import { z } from 'zod'\nimport { serviceSchema } from './schemas'\nimport { ServiceTypes } from './serviceTypes'\nexport type ServiceOptions = z.input<typeof serviceSchema> &\n Record<string, unknown>\nexport class Service {\n public fullService: ServiceOptions\n public id: string\n public type: ServiceTypes | string | Array<ServiceTypes | string>\n public serviceEndpoint: string | Array<string> | Record<string, string>",
"score": 50.284119025801964
},
{
"filename": "src/service.ts",
"retrieved_chunk": " */\n public isTypeInDidSpecRegistry(\n additionalAcceptedTypes: string | Array<string> = []\n ): boolean {\n const additionalAcceptedTypesArray =\n typeof additionalAcceptedTypes === 'string'\n ? [additionalAcceptedTypes]\n : additionalAcceptedTypes\n const allTypes = (Object.values(ServiceTypes) as Array<string>).concat(\n additionalAcceptedTypesArray",
"score": 48.30606610381631
},
{
"filename": "src/did.ts",
"retrieved_chunk": " }\n return `${p}${s}`\n }\n public addParameterKey(key: string | Array<string>): this {\n if (typeof key === 'string') {\n this.parameterKeys.push(key)\n } else if (Array.isArray(key)) {\n this.parameterKeys.push(...key)\n }\n return this",
"score": 45.43120569517788
},
{
"filename": "src/verificationMethod.ts",
"retrieved_chunk": " id: Did\n controller: Did\n type: VerificationMethodTypes | string\n publicKeyJwk?: PublicKeyJwk\n publicKeyMultibase?: PublicKeyMultibase\n public constructor(options: VerificationMethodOptions) {\n this.fullVerificationMethod = options\n const { id, controller, type, publicKeyJwk, publicKeyMultibase } =\n verificationMethodSchema.parse(options)\n this.id = id",
"score": 41.67813832033259
},
{
"filename": "src/did.ts",
"retrieved_chunk": " private path?: string\n private query?: Record<string, string>\n private fragment?: string\n private parameters?: Record<string, string>\n private parameterKeys: Array<string>\n public constructor(did: string, parameterKeys?: Array<string>) {\n const parsedDid = didUrlSchemaWithouttransformation.parse(did)\n const url = new URL(parsedDid)\n const prefixPathIndex = url.pathname.indexOf(PREFIX_PATH)\n const stripUntil = Math.min(",
"score": 40.26673668203562
}
] | typescript | public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) { |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
public capabilityDelegation?: Array<VerificationMethod | Did>
| public service?: Array<Service>
public constructor(options: DidDocumentOptions) { |
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: string | Did,
asArray = true
): ReturnBuilderWithController<this> {
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addService(service: ServiceOptions): ReturnBuilderWithService<this> {
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public findServiceByType(type: string): Service {
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/service.ts",
"retrieved_chunk": "import { z } from 'zod'\nimport { serviceSchema } from './schemas'\nimport { ServiceTypes } from './serviceTypes'\nexport type ServiceOptions = z.input<typeof serviceSchema> &\n Record<string, unknown>\nexport class Service {\n public fullService: ServiceOptions\n public id: string\n public type: ServiceTypes | string | Array<ServiceTypes | string>\n public serviceEndpoint: string | Array<string> | Record<string, string>",
"score": 50.284119025801964
},
{
"filename": "src/service.ts",
"retrieved_chunk": " */\n public isTypeInDidSpecRegistry(\n additionalAcceptedTypes: string | Array<string> = []\n ): boolean {\n const additionalAcceptedTypesArray =\n typeof additionalAcceptedTypes === 'string'\n ? [additionalAcceptedTypes]\n : additionalAcceptedTypes\n const allTypes = (Object.values(ServiceTypes) as Array<string>).concat(\n additionalAcceptedTypesArray",
"score": 48.30606610381631
},
{
"filename": "src/did.ts",
"retrieved_chunk": " }\n return `${p}${s}`\n }\n public addParameterKey(key: string | Array<string>): this {\n if (typeof key === 'string') {\n this.parameterKeys.push(key)\n } else if (Array.isArray(key)) {\n this.parameterKeys.push(...key)\n }\n return this",
"score": 45.43120569517788
},
{
"filename": "src/verificationMethod.ts",
"retrieved_chunk": " id: Did\n controller: Did\n type: VerificationMethodTypes | string\n publicKeyJwk?: PublicKeyJwk\n publicKeyMultibase?: PublicKeyMultibase\n public constructor(options: VerificationMethodOptions) {\n this.fullVerificationMethod = options\n const { id, controller, type, publicKeyJwk, publicKeyMultibase } =\n verificationMethodSchema.parse(options)\n this.id = id",
"score": 41.67813832033259
},
{
"filename": "src/did.ts",
"retrieved_chunk": " private path?: string\n private query?: Record<string, string>\n private fragment?: string\n private parameters?: Record<string, string>\n private parameterKeys: Array<string>\n public constructor(did: string, parameterKeys?: Array<string>) {\n const parsedDid = didUrlSchemaWithouttransformation.parse(did)\n const url = new URL(parsedDid)\n const prefixPathIndex = url.pathname.indexOf(PREFIX_PATH)\n const stripUntil = Math.min(",
"score": 40.26673668203562
}
] | typescript | public service?: Array<Service>
public constructor(options: DidDocumentOptions) { |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) {
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: string | Did,
asArray = true
): ReturnBuilderWithController<this> {
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public | addService(service: ServiceOptions): ReturnBuilderWithService<this> { |
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public findServiceByType(type: string): Service {
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/schemas/didDocumentSchema.ts",
"retrieved_chunk": " ),\n keyAgreement: z.optional(\n uniqueStringOrVerificationMethodsSchema('keyAgreement')\n ),\n capabilityInvocation: z.optional(\n uniqueStringOrVerificationMethodsSchema('capabilityInvocation')\n ),\n capabilityDelegation: z.optional(\n uniqueStringOrVerificationMethodsSchema('capabilityInvocation')\n ),",
"score": 23.996665062843945
},
{
"filename": "src/service.ts",
"retrieved_chunk": " public constructor(options: ServiceOptions) {\n this.fullService = options\n const { id, type, serviceEndpoint } = serviceSchema.parse(options)\n this.id = id\n this.type = type\n this.serviceEndpoint = serviceEndpoint\n }\n /**\n * Checks whether the service type is registered inside the @{link https://www.w3.org/TR/did-spec-registries/#service-types | service types}\n *",
"score": 17.61287644482406
},
{
"filename": "src/did.ts",
"retrieved_chunk": " this.query = { ...this.query, ...query }\n } else {\n this.withQuery(query)\n }\n return this\n }\n public removeQuery(): this {\n this.query = undefined\n return this\n }",
"score": 16.196974156669466
},
{
"filename": "src/did.ts",
"retrieved_chunk": " public withFragment(fragment: string): this {\n this.fragment = this.stripOptionalPrefix(fragment, PREFIX_FRAGMENT)\n return this\n }\n public removeFragment(): this {\n this.fragment = undefined\n return this\n }\n public get didParts(): DidParts {\n const parts = this.did.split(':')",
"score": 16.182003146572818
},
{
"filename": "src/did.ts",
"retrieved_chunk": " public removePath(): this {\n this.path = undefined\n return this\n }\n public withQuery(query: Record<string, string>): this {\n this.query = query\n return this\n }\n public addQuery(query: Record<string, string>): this {\n if (this.query) {",
"score": 16.182003146572818
}
] | typescript | addService(service: ServiceOptions): ReturnBuilderWithService<this> { |
import { useEffect, useLayoutEffect, useRef } from 'react';
import { PlayIcon } from '@heroicons/react/24/outline';
import MonacoEditor from '@monaco-editor/react';
import { editor } from 'monaco-editor';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import K from './Hotkey';
interface EditorProps {
onRunCode?: (code: string) => void;
showRunButton?: boolean;
}
interface CoreEditorProps extends EditorProps {
onSave: (content: string) => void;
onChange: (value: string) => void;
value: string;
}
const CoreEditor = (props: CoreEditorProps): JSX.Element => {
const ref = useRef<editor.IStandaloneCodeEditor>();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 's') {
e.preventDefault();
const content = ref.current?.getValue();
if (content !== undefined) props.onSave(content);
}
if (e.key === 'F5') {
e.preventDefault();
saveThenRunCode();
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
const saveThenRunCode = () => {
const content = ref.current?.getValue() ?? '';
props.onSave(content);
props.onRunCode?.(content);
};
return (
<section className="windowed h-full w-full">
<MonacoEditor
defaultLanguage="python"
onChange={(value) =>
value !== undefined ? props.onChange(value) : null
}
onMount={(editor) => (ref.current = editor)}
options={{
fontSize: 14,
fontFamily: 'monospace',
smoothScrolling: true,
cursorSmoothCaretAnimation: 'on',
minimap: { enabled: false },
}}
theme="vs-dark"
value={props.value}
/>
{props.showRunButton && (
<div className="absolute bottom-3 right-3 space-x-2">
<Button icon={PlayIcon} onClick={saveThenRunCode}>
Run
<K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)}
</section>
);
};
const Editor = (props: EditorProps): JSX.Element | null => {
| const { update, save } = useFilesMutations(); |
const { name, content } = useFile.Selected();
useLayoutEffect(() => {
document.title = `${name ? `${name} | ` : ''}Glide`;
}, [name]);
if (name === undefined || content === undefined) return null;
return (
<CoreEditor
{...props}
onChange={update}
onSave={(newContent) => save(name, newContent)}
value={content}
/>
);
};
export default Editor;
| src/components/Editor.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Button.tsx",
"retrieved_chunk": "import { ComponentProps, ElementType, SVGProps } from 'react';\ninterface ButtonProps extends ComponentProps<'button'> {\n icon?: ElementType<SVGProps<SVGSVGElement>>;\n}\nconst Button = (props: ButtonProps): JSX.Element => {\n const { icon: Icon, ...buttonProps } = props;\n return (\n <button\n {...buttonProps}\n className={`inline-flex justify-center rounded-lg border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 transition-transform hover:bg-blue-200 focus:outline-none focus:ring-2 focus:ring-sky-500 active:scale-95 ${",
"score": 26.944731942063648
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 25.215249461846017
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " setCommand((state) => ({ dirty: true, command: state.command + key }));\n inputRef.current?.focus();\n },\n }));\n return (\n <div className=\"flex w-full items-center rounded-lg bg-slate-800 px-2 text-slate-300 shadow-2xl shadow-slate-900 focus-within:ring-2 focus-within:ring-slate-500\">\n <ChevronRightIcon className=\"h-5\" />\n <div className=\"relative ml-2 w-full\">\n {!command.length && (\n <div className=\"pointer-events-none absolute left-0 top-0 flex h-full w-full items-center overflow-hidden\">",
"score": 15.8854934040891
},
{
"filename": "src/components/UnsavedBadge.tsx",
"retrieved_chunk": "interface UnsavedBadgeProps {\n className?: string;\n}\nconst UnsavedBadge = (props: UnsavedBadgeProps): JSX.Element => {\n return (\n <div\n className={`flex items-center space-x-2 rounded-full px-2 py-1 ring-1 ring-amber-400 ${\n props.className ?? ''\n }`}\n >",
"score": 15.734168369526916
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 14.834354000747574
}
] | typescript | const { update, save } = useFilesMutations(); |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
< | FileItem
key={name} |
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 33.72939665870862
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 33.71288308213902
},
{
"filename": "src/components/UnsavedBadge.tsx",
"retrieved_chunk": " <div className=\"h-2 w-2 rounded-full bg-amber-400\" />\n <p className=\"select-none text-xs text-amber-400\">Unsaved</p>\n </div>\n );\n};\nexport default UnsavedBadge;",
"score": 29.969403937061642
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " <button\n ref={buttonRef}\n className=\"group flex w-full min-w-0 select-none flex-row items-center justify-between rounded-lg bg-slate-700 p-3 text-slate-100 transition-transform hover:bg-slate-600 focus:outline-none focus:ring-2 focus:ring-sky-500 active:scale-95\"\n onClick={() => {\n select(props.name);\n props.onClick?.();\n }}\n tabIndex={1}\n >\n <p className=\"overflow-hidden overflow-ellipsis whitespace-nowrap opacity-90\">",
"score": 28.7253089827092
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"",
"score": 28.00822804354611
}
] | typescript | FileItem
key={name} |
import { useState } from 'react';
import { Transition } from '@headlessui/react';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import UnsavedBadge from './UnsavedBadge';
interface RenamableInputProps {
initialValue: string;
onConfirm: (value: string) => void;
}
const RenamableInput = (props: RenamableInputProps): JSX.Element => {
const [newFileName, setNewFileName] = useState<string>();
const [editing, setEditing] = useState(false);
return !editing ? (
<div
className="min-w-0 rounded-lg p-2 hover:bg-slate-800"
onClick={() => setEditing(true)}
>
<p className="text-md overflow-hidden overflow-ellipsis whitespace-nowrap">
{props.initialValue}
</p>
</div>
) : (
<input
autoFocus
className="w-fit rounded-lg bg-slate-800 bg-transparent p-2 outline-none ring-2 ring-slate-600"
onBlur={() => {
let newName = newFileName?.trim();
setEditing(false);
setNewFileName(undefined);
if (
!newName ||
newName === props.initialValue ||
newName.startsWith('.') ||
newName.endsWith('.')
)
return;
/**
* @see https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
*/
newName = newName.replace(/[/\\?%*:|"<>]/g, '_');
props.onConfirm(newName);
}}
onChange={(e) => setNewFileName(e.target.value)}
onFocus={(e) => {
const name = e.target.value;
const extensionLength = name.split('.').pop()?.length ?? 0;
e.target.setSelectionRange(0, name.length - extensionLength - 1);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
e.currentTarget.blur();
}
if (e.key === 'Escape') {
e.preventDefault();
setEditing(false);
setNewFileName(undefined);
}
}}
placeholder={props.initialValue}
type="text"
value={newFileName ?? props.initialValue}
/>
);
};
const FileName = (): JSX.Element => {
const name = useFile.SelectedName();
const unsaved = useFile.IsUnsavedOf(name);
const existingNames = useFile.NamesSet();
| const { rename } = useFilesMutations(); |
return (
<div className="flex min-w-0 items-center space-x-3">
{name && (
<RenamableInput
initialValue={name}
onConfirm={(newName) => {
if (!name) return;
if (existingNames.has(newName)) return;
rename(name, newName);
}}
/>
)}
<Transition
enter="transition-transform origin-left duration-75"
enterFrom="scale-0"
enterTo="scale-100"
leave="transition-transform origin-left duration-150"
leaveFrom="scale-100"
leaveTo="scale-0"
show={Boolean(name && unsaved)}
>
<UnsavedBadge />
</Transition>
</div>
);
};
export default FileName;
| src/components/FileName.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/hooks/useFile.ts",
"retrieved_chunk": " return fileInFiles !== fileInVault;\n });\nconst Exports = () => {\n const { files, list } = getState().vault;\n return list.map((name) => ({ name, content: files[name] }));\n};\nconst useFile = {\n SelectedName,\n Selected,\n NamesSet,",
"score": 21.6495277800427
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">",
"score": 20.895783963615884
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "import { useLayoutEffect, useRef } from 'react';\nimport { ArrowRightIcon, TrashIcon } from '@heroicons/react/24/outline';\nimport useFile from '../hooks/useFile';\nimport useFilesMutations from '../hooks/useFilesMutations';\nimport UnsavedBadge from './UnsavedBadge';\ninterface FileItemProps {\n name: string;\n onClick?: () => void;\n unsaved?: boolean;\n}",
"score": 19.480134585209473
},
{
"filename": "src/hooks/useFile.ts",
"retrieved_chunk": " NamesWithUnsaved,\n IsUnsavedOf,\n Exports,\n};\nexport default useFile;",
"score": 18.164098339514
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": "import { useEffect, useState } from 'react';\nimport { BuildingLibraryIcon } from '@heroicons/react/24/outline';\nimport useFile from '../hooks/useFile';\nimport FileName from './FileName';\nimport K from './Hotkey';\nimport Item from './Item';\nimport Library from './Library';\nconst isMac = navigator.platform.startsWith('Mac');\nconst Navigator = (): JSX.Element => {\n const [openLibrary, setOpenLibrary] = useState(true);",
"score": 17.686678085049927
}
] | typescript | const { rename } = useFilesMutations(); |
import { useEffect, useLayoutEffect, useRef } from 'react';
import { PlayIcon } from '@heroicons/react/24/outline';
import MonacoEditor from '@monaco-editor/react';
import { editor } from 'monaco-editor';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import K from './Hotkey';
interface EditorProps {
onRunCode?: (code: string) => void;
showRunButton?: boolean;
}
interface CoreEditorProps extends EditorProps {
onSave: (content: string) => void;
onChange: (value: string) => void;
value: string;
}
const CoreEditor = (props: CoreEditorProps): JSX.Element => {
const ref = useRef<editor.IStandaloneCodeEditor>();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 's') {
e.preventDefault();
const content = ref.current?.getValue();
if (content !== undefined) props.onSave(content);
}
if (e.key === 'F5') {
e.preventDefault();
saveThenRunCode();
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
const saveThenRunCode = () => {
const content = ref.current?.getValue() ?? '';
props.onSave(content);
props.onRunCode?.(content);
};
return (
<section className="windowed h-full w-full">
<MonacoEditor
defaultLanguage="python"
onChange={(value) =>
value !== undefined ? props.onChange(value) : null
}
onMount={(editor) => (ref.current = editor)}
options={{
fontSize: 14,
fontFamily: 'monospace',
smoothScrolling: true,
cursorSmoothCaretAnimation: 'on',
minimap: { enabled: false },
}}
theme="vs-dark"
value={props.value}
/>
{props.showRunButton && (
<div className="absolute bottom-3 right-3 space-x-2">
<Button icon={PlayIcon} onClick={saveThenRunCode}>
Run
<K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)}
</section>
);
};
const Editor = (props: EditorProps): JSX.Element | null => {
const { update, save } = useFilesMutations();
const { name, | content } = useFile.Selected(); |
useLayoutEffect(() => {
document.title = `${name ? `${name} | ` : ''}Glide`;
}, [name]);
if (name === undefined || content === undefined) return null;
return (
<CoreEditor
{...props}
onChange={update}
onSave={(newContent) => save(name, newContent)}
value={content}
/>
);
};
export default Editor;
| src/components/Editor.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/hooks/useFilesMutations.ts",
"retrieved_chunk": " save: (name: string, content: string) => void;\n destroy: (name: string) => void;\n draft: (autoSelect?: boolean) => void;\n select: (name: string) => void;\n update: (content: string) => void;\n create: (name: string, content: string) => void;\n}\nconst useFilesMutations = (): UseFilesMutationsHook => {\n const dispatch = useAppDispatch();\n return {",
"score": 16.08699437534377
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">",
"score": 15.31763862503136
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " type=\"text\"\n value={newFileName ?? props.initialValue}\n />\n );\n};\nconst FileName = (): JSX.Element => {\n const name = useFile.SelectedName();\n const unsaved = useFile.IsUnsavedOf(name);\n const existingNames = useFile.NamesSet();\n const { rename } = useFilesMutations();",
"score": 15.215333085663628
},
{
"filename": "src/hooks/useFilesMutations.ts",
"retrieved_chunk": " dispatch(filesActions.select(name));\n },\n update: (content: string) => {\n dispatch(filesActions.updateSelected(content));\n },\n create: (name: string, content: string) => {\n dispatch(filesActions.create({ name, content }));\n dispatch(vaultActions.save({ name, content }));\n persistor.flush();\n },",
"score": 14.646775105735117
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 13.979607230997045
}
] | typescript | content } = useFile.Selected(); |
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
| onReturn={(input) => { |
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
| src/components/Terminal.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " setCommand((state) => ({ dirty: true, command: state.command + key }));\n inputRef.current?.focus();\n },\n }));\n return (\n <div className=\"flex w-full items-center rounded-lg bg-slate-800 px-2 text-slate-300 shadow-2xl shadow-slate-900 focus-within:ring-2 focus-within:ring-slate-500\">\n <ChevronRightIcon className=\"h-5\" />\n <div className=\"relative ml-2 w-full\">\n {!command.length && (\n <div className=\"pointer-events-none absolute left-0 top-0 flex h-full w-full items-center overflow-hidden\">",
"score": 52.300002742165184
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " return (\n <section className=\"windowed h-full w-full\">\n <MonacoEditor\n defaultLanguage=\"python\"\n onChange={(value) =>\n value !== undefined ? props.onChange(value) : null\n }\n onMount={(editor) => (ref.current = editor)}\n options={{\n fontSize: 14,",
"score": 46.90030131162756
},
{
"filename": "src/components/Between.tsx",
"retrieved_chunk": " className={`h-full ${direction === 'horizontal' ? 'flex' : ''}`}\n direction={direction}\n gutterSize={15}\n sizes={sizes}\n >\n <div ref={oneRef}>{props.first}</div>\n <div ref={twoRef}>{props.second}</div>\n </Split>\n );\n};",
"score": 39.69849979836329
},
{
"filename": "src/components/UnsavedBadge.tsx",
"retrieved_chunk": " <div className=\"h-2 w-2 rounded-full bg-amber-400\" />\n <p className=\"select-none text-xs text-amber-400\">Unsaved</p>\n </div>\n );\n};\nexport default UnsavedBadge;",
"score": 37.41952342232201
},
{
"filename": "src/components/UnsavedBadge.tsx",
"retrieved_chunk": "interface UnsavedBadgeProps {\n className?: string;\n}\nconst UnsavedBadge = (props: UnsavedBadgeProps): JSX.Element => {\n return (\n <div\n className={`flex items-center space-x-2 rounded-full px-2 py-1 ring-1 ring-amber-400 ${\n props.className ?? ''\n }`}\n >",
"score": 37.19234876492968
}
] | typescript | onReturn={(input) => { |
import { useEffect, useLayoutEffect, useRef } from 'react';
import { PlayIcon } from '@heroicons/react/24/outline';
import MonacoEditor from '@monaco-editor/react';
import { editor } from 'monaco-editor';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import K from './Hotkey';
interface EditorProps {
onRunCode?: (code: string) => void;
showRunButton?: boolean;
}
interface CoreEditorProps extends EditorProps {
onSave: (content: string) => void;
onChange: (value: string) => void;
value: string;
}
const CoreEditor = (props: CoreEditorProps): JSX.Element => {
const ref = useRef<editor.IStandaloneCodeEditor>();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 's') {
e.preventDefault();
const content = ref.current?.getValue();
if (content !== undefined) props.onSave(content);
}
if (e.key === 'F5') {
e.preventDefault();
saveThenRunCode();
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
const saveThenRunCode = () => {
const content = ref.current?.getValue() ?? '';
props.onSave(content);
props.onRunCode?.(content);
};
return (
<section className="windowed h-full w-full">
<MonacoEditor
defaultLanguage="python"
onChange={(value) =>
value !== undefined ? props.onChange(value) : null
}
onMount={(editor) => (ref.current = editor)}
options={{
fontSize: 14,
fontFamily: 'monospace',
smoothScrolling: true,
cursorSmoothCaretAnimation: 'on',
minimap: { enabled: false },
}}
theme="vs-dark"
value={props.value}
/>
{props.showRunButton && (
<div className="absolute bottom-3 right-3 space-x-2">
<Button icon={PlayIcon} onClick={saveThenRunCode}>
Run
< | K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)} |
</section>
);
};
const Editor = (props: EditorProps): JSX.Element | null => {
const { update, save } = useFilesMutations();
const { name, content } = useFile.Selected();
useLayoutEffect(() => {
document.title = `${name ? `${name} | ` : ''}Glide`;
}, [name]);
if (name === undefined || content === undefined) return null;
return (
<CoreEditor
{...props}
onChange={update}
onSave={(newContent) => save(name, newContent)}
value={content}
/>
);
};
export default Editor;
| src/components/Editor.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }}\n onClickRestart={props.onRestart}\n />\n </div>\n {props.showStopButton && (\n <div className=\"absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100\">\n <Button icon={StopIcon} onClick={props.onStop}>\n Stop\n </Button>\n </div>",
"score": 45.691892998873435
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 35.22157054898086
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " ))}\n </div>\n <div className=\"mt-10 space-x-2\">\n <Button\n icon={PlusIcon}\n onClick={() => {\n draft(true);\n props.onClose();\n }}\n >",
"score": 33.131963216823785
},
{
"filename": "src/components/Button.tsx",
"retrieved_chunk": "import { ComponentProps, ElementType, SVGProps } from 'react';\ninterface ButtonProps extends ComponentProps<'button'> {\n icon?: ElementType<SVGProps<SVGSVGElement>>;\n}\nconst Button = (props: ButtonProps): JSX.Element => {\n const { icon: Icon, ...buttonProps } = props;\n return (\n <button\n {...buttonProps}\n className={`inline-flex justify-center rounded-lg border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 transition-transform hover:bg-blue-200 focus:outline-none focus:ring-2 focus:ring-sky-500 active:scale-95 ${",
"score": 30.858033088993352
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 29.982561959361135
}
] | typescript | K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)} |
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
| <TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()} |
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
| src/components/Terminal.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " setCommand((state) => ({ dirty: true, command: state.command + key }));\n inputRef.current?.focus();\n },\n }));\n return (\n <div className=\"flex w-full items-center rounded-lg bg-slate-800 px-2 text-slate-300 shadow-2xl shadow-slate-900 focus-within:ring-2 focus-within:ring-slate-500\">\n <ChevronRightIcon className=\"h-5\" />\n <div className=\"relative ml-2 w-full\">\n {!command.length && (\n <div className=\"pointer-events-none absolute left-0 top-0 flex h-full w-full items-center overflow-hidden\">",
"score": 29.660879617128167
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": " {...buttonProps}\n className={`relative cursor-pointer ${props.className ?? ''}`}\n >\n {props.children}\n <input\n accept=\"text/csv, text/x-python-script, text/x-python, .py, .csv, text/plain\"\n className=\"absolute bottom-0 left-0 right-0 top-0 cursor-pointer opacity-0\"\n onChange={handleUpload}\n type=\"file\"\n />",
"score": 28.2715981918391
},
{
"filename": "src/components/UnsavedBadge.tsx",
"retrieved_chunk": "interface UnsavedBadgeProps {\n className?: string;\n}\nconst UnsavedBadge = (props: UnsavedBadgeProps): JSX.Element => {\n return (\n <div\n className={`flex items-center space-x-2 rounded-full px-2 py-1 ring-1 ring-amber-400 ${\n props.className ?? ''\n }`}\n >",
"score": 24.265358984817652
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " as={Fragment}\n enter=\"transition ease-out duration-100\"\n enterFrom=\"transform opacity-0 scale-95\"\n enterTo=\"transform opacity-100 scale-100\"\n leave=\"transition ease-in duration-75\"\n leaveFrom=\"transform opacity-100 scale-100\"\n leaveTo=\"transform opacity-0 scale-95\"\n >\n <Menu.Items className=\"absolute bottom-11 right-0 z-40 origin-bottom-right divide-y-2 divide-slate-700 rounded-md bg-slate-800 shadow-2xl ring-2 ring-slate-700\">\n <div className=\"px-1 py-1\">",
"score": 23.7088284310585
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " fontFamily: 'monospace',\n smoothScrolling: true,\n cursorSmoothCaretAnimation: 'on',\n minimap: { enabled: false },\n }}\n theme=\"vs-dark\"\n value={props.value}\n />\n {props.showRunButton && (\n <div className=\"absolute bottom-3 right-3 space-x-2\">",
"score": 22.623747200899142
}
] | typescript | <TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()} |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
| {files.map(({ name, unsaved }) => (
<FileItem
key={name} |
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 33.72939665870862
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 33.71288308213902
},
{
"filename": "src/components/UnsavedBadge.tsx",
"retrieved_chunk": " <div className=\"h-2 w-2 rounded-full bg-amber-400\" />\n <p className=\"select-none text-xs text-amber-400\">Unsaved</p>\n </div>\n );\n};\nexport default UnsavedBadge;",
"score": 29.969403937061642
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " <button\n ref={buttonRef}\n className=\"group flex w-full min-w-0 select-none flex-row items-center justify-between rounded-lg bg-slate-700 p-3 text-slate-100 transition-transform hover:bg-slate-600 focus:outline-none focus:ring-2 focus:ring-sky-500 active:scale-95\"\n onClick={() => {\n select(props.name);\n props.onClick?.();\n }}\n tabIndex={1}\n >\n <p className=\"overflow-hidden overflow-ellipsis whitespace-nowrap opacity-90\">",
"score": 28.7253089827092
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"",
"score": 28.00822804354611
}
] | typescript | {files.map(({ name, unsaved }) => (
<FileItem
key={name} |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
<FileItem
key={name}
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
< | FileUploader
icon={ArrowUpTrayIcon} |
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": " </Button>\n );\n};\nexport default FileUploader;",
"score": 11.20173354298266
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 10.878678349978195
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }}\n onClickRestart={props.onRestart}\n />\n </div>\n {props.showStopButton && (\n <div className=\"absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100\">\n <Button icon={StopIcon} onClick={props.onStop}>\n Stop\n </Button>\n </div>",
"score": 10.487509972420064
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {",
"score": 10.075267621186022
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuHeader>Interpreter</MenuHeader>\n <MenuItem icon={ArrowPathIcon} onClick={props.onClickRestart}>\n Restart\n </MenuItem>\n <MenuItem icon={StopIcon} onClick={props.onClickForceStop}>\n Force stop\n </MenuItem>\n </div>\n <div className=\"px-1 py-1\">\n <MenuHeader>Console</MenuHeader>",
"score": 8.9528669741002
}
] | typescript | FileUploader
icon={ArrowUpTrayIcon} |
import {
loadPyodide,
PyodideInterface,
PyProxy,
PyProxyAwaitable,
PyProxyCallable,
PyProxyDict,
} from 'pyodide';
import consoleScript from '../assets/console.py';
/**
* @see https://pyodide.org/en/stable/usage/api/python-api/console.html#pyodide.console.ConsoleFuture.syntax_check
*/
type SyntaxCheck = 'syntax-error' | 'incomplete' | 'complete';
interface Message<T extends Record<string, unknown>> {
type: keyof T;
payload: any;
}
interface RunExportableData {
code: string;
exports?: { name: string; content: string }[];
}
let pyodide: PyodideInterface;
let interruptBuffer: Uint8Array | null;
let await_fut: PyProxyCallable;
let repr_shorten: PyProxyCallable;
let pyconsole: PyProxy;
let clear_console: PyProxyCallable;
let create_console: PyProxyCallable;
const PS1 = '\u001b[32;1m>>> \u001b[0m' as const;
const PS2 = '\u001b[32m... \u001b[0m' as const;
const RUN_CODE = '\u001b[3m\u001b[32m<run code>\u001b[0m' as const;
const post = {
write: (text: string) => postMessage({ type: 'write', payload: text }),
writeln: (line: string) => postMessage({ type: 'writeln', payload: line }),
error: (message: string) => postMessage({ type: 'error', payload: message }),
system: (message: string) =>
postMessage({ type: 'system', payload: message }),
lock: () => postMessage({ type: 'lock' }),
unlock: () => postMessage({ type: 'unlock' }),
prompt: (newLine = true) => post.write(`${newLine ? '\n' : ''}${PS1}`),
promptPending: () => post.write(PS2),
};
const setUpConsole = (globals?: PyProxyDict) => {
pyconsole?.destroy();
pyconsole = create_console(globals);
};
const setUpREPLEnvironment = () => {
const globals = pyodide.globals.get('dict')();
pyodide | .runPython(consoleScript, { globals }); |
repr_shorten = globals.get('repr_shorten');
await_fut = globals.get('await_fut');
create_console = globals.get('create_console');
clear_console = globals.get('clear_console');
setUpConsole();
return globals.get('BANNER') as string;
};
const preparePyodide = async () => {
const newPyodide = await loadPyodide();
newPyodide.setStdout({ batched: post.writeln });
newPyodide.setStderr({ batched: post.error });
pyodide = newPyodide;
if (interruptBuffer) pyodide.setInterruptBuffer(interruptBuffer);
/**
* Replaces Pyodide's `js` import with a stub `object`. This must also be
* paired with some `del sys.modules['js']` in Pyodide's initialisation.
*/
pyodide.registerJsModule('js', {});
const banner = setUpREPLEnvironment();
post.writeln(banner);
post.prompt(false);
post.unlock();
return newPyodide;
};
const prepareExports = (exports?: { name: string; content: string }[]) => {
let newExports = new Set<string>();
exports?.forEach(({ name, content }) => {
pyodide.FS.writeFile(name, content, { encoding: 'utf-8' });
newExports.add(name);
});
const oldExports = pyodide.FS.readdir('.') as string[];
oldExports.forEach((name) => {
if (name === '.' || name === '..' || newExports.has(name)) return;
pyodide.FS.unlink(name);
});
};
/**
* Pyodide may sometimes not catch `RecursionError`s and excessively
* recursive code spills as JavaScript `RangeError`, causing Pyodide to
* fatally crash. We need to restart Pyodide in this case.
* @see https://github.com/pyodide/pyodide/issues/951
*/
const handleRangeErrorAndRestartPyodide = async (error: unknown) => {
if (!(error instanceof RangeError)) return;
post.system(
'\nOops, something happened and we have to restart the interpreter. ' +
"Don't worry, it's not your fault. " +
'You may continue once you see the prompt again.\n',
);
await preparePyodide();
};
const listeners = {
initialize: async (newInterruptBuffer?: Uint8Array) => {
pyodide ??= await preparePyodide();
if (!newInterruptBuffer) return;
pyodide.setInterruptBuffer(newInterruptBuffer);
interruptBuffer = newInterruptBuffer;
},
run: async ({ code, exports }: RunExportableData) => {
pyodide ??= await preparePyodide();
post.writeln(RUN_CODE);
try {
post.lock();
prepareExports(exports);
await pyodide.loadPackagesFromImports(code);
const globals = pyodide.globals.get('dict')();
/**
* `await pyodide.runPythonAsync(code)` is not used because it raises
* an uncatchable `PythonError` when Pyodide emits a `KeyboardInterrupt`.
* @see https://github.com/pyodide/pyodide/issues/2141
*/
const result = pyodide.runPython(code, { globals });
setUpConsole(globals);
post.writeln(result?.toString());
} catch (error) {
if (!(error instanceof Error)) throw error;
post.error(error.message);
handleRangeErrorAndRestartPyodide(error);
} finally {
post.prompt();
post.unlock();
}
},
replClear: async () => {
try {
clear_console(pyconsole);
await await_fut(pyconsole.push(''));
} finally {
post.error('\nKeyboardInterrupt');
post.prompt();
}
},
replInput: async ({ code, exports }: RunExportableData) => {
post.writeln(code);
const future = pyconsole.push(code) as PyProxy;
const status = future.syntax_check as SyntaxCheck;
switch (status) {
case 'syntax-error':
post.error(future.formatted_error.trimEnd());
post.prompt();
return;
case 'incomplete':
post.promptPending();
return;
case 'complete':
break;
default:
throw new Error(`Unexpected type: ${status}`);
}
prepareExports(exports);
const wrapped = await_fut(future) as PyProxyAwaitable;
try {
const [value] = await wrapped;
if (value !== undefined) {
const repr = repr_shorten.callKwargs(value, {
separator: '\n<long output truncated>\n',
}) as string;
post.writeln(repr);
}
if (pyodide.isPyProxy(value)) value.destroy();
} catch (error) {
if (!(error instanceof Error)) throw error;
const message = future.formatted_error || error.message;
post.error(message.trimEnd());
handleRangeErrorAndRestartPyodide(error);
} finally {
post.prompt();
future.destroy();
wrapped.destroy();
}
},
};
onmessage = async (event: MessageEvent<Message<typeof listeners>>) => {
listeners[event.data.type]?.(event.data.payload);
};
| src/workers/interpreter.worker.ts | NUSSOC-glide-3ab6925 | [
{
"filename": "src/hooks/useFilesMutations.ts",
"retrieved_chunk": " },\n destroy: (name: string) => {\n dispatch(filesActions.destroy(name));\n dispatch(vaultActions.destroy(name));\n persistor.flush();\n },\n draft: (autoSelect?: boolean) => {\n dispatch(filesActions.draft(autoSelect));\n },\n select: (name: string) => {",
"score": 5.501534616998128
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }, []);\n const write = (text: string, line = true) => {\n const trimmed = text.replace(/\\n/g, '\\r\\n');\n const xterm = xtermRef.current;\n if (!xterm) return;\n const writer = (text: string) =>\n line ? xterm.writeln(text) : xterm.write(text);\n try {\n writer(trimmed);\n } catch (error) {",
"score": 5.264229516440562
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " if (!(error instanceof Error)) throw error;\n console.log('oops', error.message);\n xterm.clear();\n writer(trimmed);\n }\n };\n useImperativeHandle(ref, () => ({\n append: (result?: string) => write(result ?? ''),\n write: (result?: string) => write(result ?? '', false),\n error: (result?: string) =>",
"score": 5.131988004595224
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " const interpreter = useInterpreter({\n write: (text: string) => consoleRef.current?.write(text),\n writeln: (text: string) => consoleRef.current?.append(text),\n error: (text: string) => consoleRef.current?.error(text),\n system: (text: string) => consoleRef.current?.system(text),\n exports: useFile.Exports,\n lock: () => setRunning(true),\n unlock: () => setRunning(false),\n });\n return (",
"score": 4.520669062444181
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">",
"score": 3.8103574484249045
}
] | typescript | .runPython(consoleScript, { globals }); |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
<FileItem
key={name}
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
| onUpload={(name, content) => { |
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 16.28270731302097
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": " </Button>\n );\n};\nexport default FileUploader;",
"score": 11.20173354298266
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 10.878678349978195
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }}\n onClickRestart={props.onRestart}\n />\n </div>\n {props.showStopButton && (\n <div className=\"absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100\">\n <Button icon={StopIcon} onClick={props.onStop}>\n Stop\n </Button>\n </div>",
"score": 10.487509972420064
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {",
"score": 10.075267621186022
}
] | typescript | onUpload={(name, content) => { |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, | unsaved }) => (
<FileItem
key={name} |
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 33.72939665870862
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 33.71288308213902
},
{
"filename": "src/components/UnsavedBadge.tsx",
"retrieved_chunk": " <div className=\"h-2 w-2 rounded-full bg-amber-400\" />\n <p className=\"select-none text-xs text-amber-400\">Unsaved</p>\n </div>\n );\n};\nexport default UnsavedBadge;",
"score": 29.969403937061642
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " <button\n ref={buttonRef}\n className=\"group flex w-full min-w-0 select-none flex-row items-center justify-between rounded-lg bg-slate-700 p-3 text-slate-100 transition-transform hover:bg-slate-600 focus:outline-none focus:ring-2 focus:ring-sky-500 active:scale-95\"\n onClick={() => {\n select(props.name);\n props.onClick?.();\n }}\n tabIndex={1}\n >\n <p className=\"overflow-hidden overflow-ellipsis whitespace-nowrap opacity-90\">",
"score": 28.7253089827092
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"",
"score": 28.00822804354611
}
] | typescript | unsaved }) => (
<FileItem
key={name} |
import { useEffect, useLayoutEffect, useRef } from 'react';
import { PlayIcon } from '@heroicons/react/24/outline';
import MonacoEditor from '@monaco-editor/react';
import { editor } from 'monaco-editor';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import K from './Hotkey';
interface EditorProps {
onRunCode?: (code: string) => void;
showRunButton?: boolean;
}
interface CoreEditorProps extends EditorProps {
onSave: (content: string) => void;
onChange: (value: string) => void;
value: string;
}
const CoreEditor = (props: CoreEditorProps): JSX.Element => {
const ref = useRef<editor.IStandaloneCodeEditor>();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 's') {
e.preventDefault();
const content = ref.current?.getValue();
if (content !== undefined) props.onSave(content);
}
if (e.key === 'F5') {
e.preventDefault();
saveThenRunCode();
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
const saveThenRunCode = () => {
const content = ref.current?.getValue() ?? '';
props.onSave(content);
props.onRunCode?.(content);
};
return (
<section className="windowed h-full w-full">
<MonacoEditor
defaultLanguage="python"
onChange={(value) =>
value !== undefined ? props.onChange(value) : null
}
onMount={(editor) => (ref.current = editor)}
options={{
fontSize: 14,
fontFamily: 'monospace',
smoothScrolling: true,
cursorSmoothCaretAnimation: 'on',
minimap: { enabled: false },
}}
theme="vs-dark"
value={props.value}
/>
{props.showRunButton && (
<div className="absolute bottom-3 right-3 space-x-2">
<Button icon={PlayIcon} onClick={saveThenRunCode}>
Run
| <K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)} |
</section>
);
};
const Editor = (props: EditorProps): JSX.Element | null => {
const { update, save } = useFilesMutations();
const { name, content } = useFile.Selected();
useLayoutEffect(() => {
document.title = `${name ? `${name} | ` : ''}Glide`;
}, [name]);
if (name === undefined || content === undefined) return null;
return (
<CoreEditor
{...props}
onChange={update}
onSave={(newContent) => save(name, newContent)}
value={content}
/>
);
};
export default Editor;
| src/components/Editor.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }}\n onClickRestart={props.onRestart}\n />\n </div>\n {props.showStopButton && (\n <div className=\"absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100\">\n <Button icon={StopIcon} onClick={props.onStop}>\n Stop\n </Button>\n </div>",
"score": 47.51808971657055
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 37.16755619739987
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " ))}\n </div>\n <div className=\"mt-10 space-x-2\">\n <Button\n icon={PlusIcon}\n onClick={() => {\n draft(true);\n props.onClose();\n }}\n >",
"score": 34.541872557780984
},
{
"filename": "src/components/Button.tsx",
"retrieved_chunk": "import { ComponentProps, ElementType, SVGProps } from 'react';\ninterface ButtonProps extends ComponentProps<'button'> {\n icon?: ElementType<SVGProps<SVGSVGElement>>;\n}\nconst Button = (props: ButtonProps): JSX.Element => {\n const { icon: Icon, ...buttonProps } = props;\n return (\n <button\n {...buttonProps}\n className={`inline-flex justify-center rounded-lg border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 transition-transform hover:bg-blue-200 focus:outline-none focus:ring-2 focus:ring-sky-500 active:scale-95 ${",
"score": 31.954580245902257
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 29.982561959361135
}
] | typescript | <K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)} |
import { useEffect, useState } from 'react';
import { BuildingLibraryIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import FileName from './FileName';
import K from './Hotkey';
import Item from './Item';
import Library from './Library';
const isMac = navigator.platform.startsWith('Mac');
const Navigator = (): JSX.Element => {
const [openLibrary, setOpenLibrary] = useState(true);
const name = useFile.SelectedName();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = isMac ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 'o') {
e.preventDefault();
setOpenLibrary(true);
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
return (
<>
<nav className="flex items-center justify-between space-x-2">
<FileName />
<div className="flex flex-row items-center space-x-2">
{name && (
<Item
className="text-slate-400"
onClick={() => {
window.dispatchEvent(
new KeyboardEvent('keydown', {
key: 's',
metaKey: isMac,
ctrlKey: !isMac,
}),
);
}}
>
Save < | K of="Mod+S" />
</Item>
)} |
<Item
className="text-slate-400"
icon={BuildingLibraryIcon}
onClick={() => setOpenLibrary(true)}
>
Library <K of="Mod+O" />
</Item>
</div>
</nav>
<Library onClose={() => setOpenLibrary(false)} open={openLibrary} />
</>
);
};
export default Navigator;
| src/components/Navigator.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Hotkey.tsx",
"retrieved_chunk": "interface HotkeyProps {\n of: string;\n className?: string;\n}\nconst isMac = navigator.platform.startsWith('Mac');\nconst CONVERTED_KEYS = isMac\n ? {\n Mod: '⌘',\n Alt: '⌥',\n Shift: '⇧',",
"score": 22.951470393151272
},
{
"filename": "src/components/Hotkey.tsx",
"retrieved_chunk": "const convert = (key: string): string =>\n key in CONVERTED_KEYS ? CONVERTED_KEYS[key as ConvertibleKeys] : key;\nconst Hotkey = (props: HotkeyProps): JSX.Element => {\n const { of: hotkey } = props;\n const keys = hotkey.split(SEPARATOR);\n if (isMac)\n return <kbd className={props.className}>{keys.map(convert).join('')}</kbd>;\n return (\n <>\n {keys",
"score": 9.958030689060685
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;\n if (isMod && e.key === 's') {\n e.preventDefault();\n const content = ref.current?.getValue();\n if (content !== undefined) props.onSave(content);\n }\n if (e.key === 'F5') {\n e.preventDefault();\n saveThenRunCode();\n }",
"score": 8.748992339749336
},
{
"filename": "src/components/Hotkey.tsx",
"retrieved_chunk": "const K = Hotkey;\nexport default K;",
"score": 7.392146875293755
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {",
"score": 7.222501276535233
}
] | typescript | K of="Mod+S" />
</Item>
)} |
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
| <Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)} |
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
| src/components/Terminal.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " fontFamily: 'monospace',\n smoothScrolling: true,\n cursorSmoothCaretAnimation: 'on',\n minimap: { enabled: false },\n }}\n theme=\"vs-dark\"\n value={props.value}\n />\n {props.showRunButton && (\n <div className=\"absolute bottom-3 right-3 space-x-2\">",
"score": 34.33143174531851
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " ))}\n </div>\n <div className=\"mt-10 space-x-2\">\n <Button\n icon={PlusIcon}\n onClick={() => {\n draft(true);\n props.onClose();\n }}\n >",
"score": 33.46758632186335
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 32.355956453220855
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuHeader>Interpreter</MenuHeader>\n <MenuItem icon={ArrowPathIcon} onClick={props.onClickRestart}>\n Restart\n </MenuItem>\n <MenuItem icon={StopIcon} onClick={props.onClickForceStop}>\n Force stop\n </MenuItem>\n </div>\n <div className=\"px-1 py-1\">\n <MenuHeader>Console</MenuHeader>",
"score": 26.21018356579176
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " {props.children}\n </Menu.Item>\n);\nconst TerminalMenu = (props: TerminalMenuProps): JSX.Element => {\n return (\n <Menu as=\"div\" className=\"relative inline-block text-left\">\n <Menu.Button className=\"rounded-md bg-slate-500 bg-opacity-20 p-2 transition-transform hover:bg-opacity-30 active:scale-95\">\n <Bars3Icon aria-hidden=\"true\" className=\"h-5 w-5\" />\n </Menu.Button>\n <Transition",
"score": 25.675497685380936
}
] | typescript | <Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)} |
import { useEffect, useState } from 'react';
import { BuildingLibraryIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import FileName from './FileName';
import K from './Hotkey';
import Item from './Item';
import Library from './Library';
const isMac = navigator.platform.startsWith('Mac');
const Navigator = (): JSX.Element => {
const [openLibrary, setOpenLibrary] = useState(true);
const name = useFile.SelectedName();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = isMac ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 'o') {
e.preventDefault();
setOpenLibrary(true);
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
return (
<>
<nav className="flex items-center justify-between space-x-2">
<FileName />
<div className="flex flex-row items-center space-x-2">
{name && (
<Item
className="text-slate-400"
onClick={() => {
window.dispatchEvent(
new KeyboardEvent('keydown', {
key: 's',
metaKey: isMac,
ctrlKey: !isMac,
}),
);
}}
>
| Save <K of="Mod+S" />
</Item>
)} |
<Item
className="text-slate-400"
icon={BuildingLibraryIcon}
onClick={() => setOpenLibrary(true)}
>
Library <K of="Mod+O" />
</Item>
</div>
</nav>
<Library onClose={() => setOpenLibrary(false)} open={openLibrary} />
</>
);
};
export default Navigator;
| src/components/Navigator.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Hotkey.tsx",
"retrieved_chunk": "interface HotkeyProps {\n of: string;\n className?: string;\n}\nconst isMac = navigator.platform.startsWith('Mac');\nconst CONVERTED_KEYS = isMac\n ? {\n Mod: '⌘',\n Alt: '⌥',\n Shift: '⇧',",
"score": 22.951470393151272
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;\n if (isMod && e.key === 's') {\n e.preventDefault();\n const content = ref.current?.getValue();\n if (content !== undefined) props.onSave(content);\n }\n if (e.key === 'F5') {\n e.preventDefault();\n saveThenRunCode();\n }",
"score": 15.082409534321314
},
{
"filename": "src/components/Hotkey.tsx",
"retrieved_chunk": "const convert = (key: string): string =>\n key in CONVERTED_KEYS ? CONVERTED_KEYS[key as ConvertibleKeys] : key;\nconst Hotkey = (props: HotkeyProps): JSX.Element => {\n const { of: hotkey } = props;\n const keys = hotkey.split(SEPARATOR);\n if (isMac)\n return <kbd className={props.className}>{keys.map(convert).join('')}</kbd>;\n return (\n <>\n {keys",
"score": 13.912258805520112
},
{
"filename": "src/components/Hotkey.tsx",
"retrieved_chunk": "const K = Hotkey;\nexport default K;",
"score": 7.392146875293755
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {",
"score": 7.222501276535233
}
] | typescript | Save <K of="Mod+S" />
</Item>
)} |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
<FileItem
key={name}
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload= | {(name, content) => { |
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 16.28270731302097
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": " </Button>\n );\n};\nexport default FileUploader;",
"score": 11.20173354298266
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": " if (!files?.length) return;\n const file = Array.from(files)[0];\n const reader = new FileReader();\n reader.onload = ({ target }) =>\n props.onUpload?.(file.name, target?.result as string);\n reader.readAsText(file);\n e.target.value = '';\n };\n return (\n <Button",
"score": 8.509944094387782
},
{
"filename": "src/hooks/useFilesMutations.ts",
"retrieved_chunk": " save: (name: string, content: string) => void;\n destroy: (name: string) => void;\n draft: (autoSelect?: boolean) => void;\n select: (name: string) => void;\n update: (content: string) => void;\n create: (name: string, content: string) => void;\n}\nconst useFilesMutations = (): UseFilesMutationsHook => {\n const dispatch = useAppDispatch();\n return {",
"score": 8.377692722690197
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }}\n onClickRestart={props.onRestart}\n />\n </div>\n {props.showStopButton && (\n <div className=\"absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100\">\n <Button icon={StopIcon} onClick={props.onStop}>\n Stop\n </Button>\n </div>",
"score": 8.079653822179615
}
] | typescript | {(name, content) => { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.